The What, How, and Why of Void Pointers in C and C++?
Summary
TLDRIn this educational video, the concept of void pointers is demystified for beginner programmers. The host explains that void pointers, which lack type information, essentially point to 'nothing' or rather, no specific type. They serve as a flexible way to store any memory address without making assumptions about the data it points to. The video illustrates void pointers' functionality with examples, including using them with memory allocation functions like malloc and free, which return and accept void pointers respectively. The host also highlights the difference in handling void pointers between C and C++, where C++ requires an explicit cast due to its stricter type safety. The aim is to clarify the use of void pointers and to help viewers overcome the initial confusion they might face when encountering them in programming.
Takeaways
- 😀 The video is aimed at beginner programmers who are familiar with pointers but encounter confusion with void pointers.
- 🔍 The term 'void' in programming is first encountered in the context of functions that do not return any value.
- 🤔 A void pointer is a pointer that does not have type information, essentially a pointer to 'nothing' or 'no type'.
- 📌 Void pointers are used to store any type of address without making assumptions about the data stored at that address.
- 💡 The size of a void pointer is the same as any other pointer on a given system, as they all store addresses.
- 🚫 You cannot directly dereference a void pointer because it lacks type information, but you can cast it to a specific pointer type to dereference it.
- 🔧 Void pointers are useful in scenarios where you need to store generic memory addresses, such as with memory allocation functions like malloc.
- 🛠️ Functions like malloc and free use void pointers because they are concerned with the size of the memory block rather than the type of data it holds.
- 🔄 When using void pointers, it's important to cast them to the appropriate pointer type before dereferencing to avoid errors.
- ⚠️ There is a difference in how C and C++ handle assigning void pointers to other pointer types, with C being more lenient and C++ requiring an explicit cast.
Q & A
What is the main topic discussed in the video?
-The main topic discussed in the video is void pointers, their purpose, and how they are used in programming, particularly in C and C++.
What does the term 'void' signify in the context of a function?
-In the context of a function, 'void' signifies that the function does not have a result type and does not produce a value upon completion.
What is a void pointer according to the video?
-A void pointer is a pointer that does not have type information attached to it. It stores an address in memory without making any assumptions about what is stored at that location.
Why might someone want to use a void pointer?
-One might want to use a void pointer when they want to store generic memory addresses without caring about the type of data those addresses point to.
How does the size of a void pointer compare to other pointers?
-The size of a void pointer is the same as other pointers, as they all store an address in memory, which is typically the size of a memory address on the system (e.g., 8 bytes on the presenter's machine).
What is the issue with dereferencing a void pointer directly?
-The issue with dereferencing a void pointer directly is that the compiler does not have type information, so it cannot perform operations on the data at the address the void pointer is storing.
How can a void pointer be made to work like a regular pointer?
-A void pointer can be made to work like a regular pointer by casting it to a specific pointer type, which provides the necessary type information for the compiler to perform operations on the data.
What is the practical use of void pointers in memory allocation?
-Void pointers are used in memory allocation functions like malloc, because these functions return a generic pointer to a block of memory without caring about the type of data that will be stored in it.
How does the video demonstrate the use of void pointers with malloc and free?
-The video demonstrates assigning a void pointer to the result of malloc to dynamically allocate memory and then casting the void pointer to an int pointer before using it. It also shows passing a void pointer to the free function to deallocate memory.
What is the difference between how C and C++ handle assigning a void pointer to another pointer type?
-C allows assigning a void pointer to another pointer type without a cast, while C++ requires an explicit cast to acknowledge the change from one pointer type to another, reflecting C++'s stronger type safety.
Why is it important to understand the difference between C and C++ when using void pointers?
-Understanding the difference is important for writing portable code that works in both languages and for avoiding type-related bugs that can occur when pointers are not properly cast.
Outlines
📌 Introduction to Void Pointers
The video begins with an introduction to void pointers, which are pointers without type information. The concept can be confusing for beginner programmers, and the video aims to clarify this by explaining what a void pointer is and why one might use it. The host also mentions that viewers might have unknowingly used void pointers before. The video promises to discuss examples of void pointers and a subtle difference between C and C++ that could save viewers time. The host expresses gratitude to supporters and mentions Patreon as a way to access example code and monthly office hours.
🔍 Understanding Void Pointers and Their Size
This paragraph delves into the concept of void pointers, comparing them to regular pointers and explaining that they store addresses without any type information. The host uses the analogy of 'void' meaning 'no type' rather than 'nothing'. The video demonstrates that both void pointers and int pointers have the same size in memory, which is eight bytes on the host's machine. The host also shows that it is possible to assign the address stored in an int pointer to a void pointer, emphasizing that void pointers are still pointers that store addresses.
🚫 Limitations and Usage of Void Pointers
The host explains the limitations of void pointers, such as the inability to dereference them directly due to the lack of type information. However, this limitation can be overcome with type casting, which allows the programmer to treat a void pointer as if it were another type of pointer. The video provides an example of casting a void pointer to an int pointer and dereferencing it to store an integer value. The host also discusses practical uses of void pointers, such as in memory allocation with malloc and free, and in functions like memcpy, which do not require type information and work with raw memory addresses.
🛠️ Practical Examples and C vs. C++ Pointer Assignment
The video provides practical examples of using void pointers, including dynamic memory allocation with malloc and copying memory with memcpy. The host also discusses the difference between C and C++ in handling pointer assignments. In C, assigning a void pointer to an int pointer is allowed, while C++ requires an explicit cast to acknowledge the change in pointer types. The host emphasizes the importance of being aware of these differences and suggests including the cast for more portable code between the two languages.
Mindmap
Keywords
💡Pointers
💡Void Pointers
💡Type Information
💡Memory Allocation
💡Dereferencing
💡Casting
💡Function Result Type
💡Generic Memory Addresses
💡C vs. C++
💡Memory Size
Highlights
Introduction to void pointers, which are pointers without type information.
Explanation of why void pointers might be used and their utility in programming.
Void functions in C and their meaning as functions without a result type.
Demonstration of a void function that prints 'hello' and the inability to assign its return value.
Introduction of the concept of a variable pointer to void, which points to no specific type.
Comparison of void pointers to regular pointers, emphasizing that they both store addresses.
Code example showing the size of void pointers and int pointers, highlighting their equivalence in memory size.
Assignment of an address value between a void pointer and an int pointer, demonstrating their interchangeability.
Explanation of the limitations of void pointers, such as the inability to dereference them without a cast.
Illustration of how to use a cast to dereference a void pointer and assign a value to it.
The subtle difference between C and C++ regarding void pointers and type casting.
Practical use case of void pointers in memory allocation with malloc and free functions.
Example of using memcpy, which utilizes void pointers for generic memory operations.
Discussion on the benefits of void pointers for storing generic memory addresses.
Code example demonstrating assigning malloc's result to both void and int pointers and the necessity of casting in C++.
Final thoughts on the importance of understanding void pointers for writing portable code between C and C++.
Encouragement for viewers to like, subscribe, and interact with the content for better visibility on YouTube.
Transcripts
today i want to talk about pointers
specifically pointers that don't have
type information are also known as void
pointers
[Music]
hey everybody welcome back today's video
is for the beginners for fairly beginner
programmers out there who think that
you've finally wrapped your head around
pointers but then you see something like
this and you're not really sure what to
make of it because this causes a serious
moment of pause for a lot of beginners
so i thought today we would talk about
it talk about what a void pointer is why
you might want to use one and we'll also
talk about some examples where you may
have already used a void pointer and you
just didn't realize it also at the end
i'm going to talk a little bit about a
subtle difference between c and c plus
plus might save you some time but first
a big thank you to all of you who
support this channel through patreon
buying merch and online classes also for
those of you that are curious about
where you can get example code from my
videos you can get that through patreon
and you can get access to my monthly
office hour so now back to void pointers
if you look long enough into the void
the void begins to look back through you
i don't know if nietzsche was talking
about new programmers but sometimes the
concept of void takes a second to get a
grip on now the first time you see void
is probably when you are looking at a
void function maybe something like this
and we make a quick function and let's
just say it's a simple function that
prints out
the word hello with a newline character
nothing complicated about that so in
this case the void simply says that this
function does not have a result type it
doesn't produce a result it doesn't give
us a value when it's done so if i come
down here in main i can definitely call
say hello and this is going to work just
fine now let's make sure just by coming
down here and compiling with my make
file i am using a make file you can
check it out here nothing complicated
just a really basic make file if you
haven't seen make be sure to check it
out on my other videos that deal with
make and actually hold up really quick i
just noticed i was editing my c plus
example let's do this over in c and
compile that one we'll come back to c
plus plus later but if i run example
here then you will see that it works
just fine it prints out hello so no
worries but note that i can't do
something like this i can't say result
equals say hello like this if i try to
do this i'm going to get an error
because it says hey look you're trying
to assign to an integer a value void
doesn't have any type information it's
not a variable simply the compiler just
doesn't know how to take nothing no
variable no result and produce an int
out of it so it gives us an error so
hopefully that makes sense hopefully
that's straightforward enough and i'll
leave this up here but so what if what
about if i come down here and say
something like void star p we understand
what it means for a function to be void
mean it doesn't return anything but what
does it mean to have a variable p which
is a pointer that points to void which
may be up till now we've thought of as
nothing so is this a pointer to nothing
okay so calm down calm down you see at
least in this case it's probably more
helpful to think of void as meaning no
type rather than nothing so we can think
of this as a pointer but we have no type
information that is attached to that
pointer so the compiler is storing an
address for us in memory but it's not
making any assumptions about what is
stored at that location in memory but
really what i want to emphasize is that
it is still a pointer just like any
other pointer it stores an address and
just to make this clear what i want to
do is to come down here and we'll just
add a little bit to our program first
thing i'm going to add an int pointer
call this p2 or let's call this ip this
might be the kind of pointer that you
maybe were introduced to and let's come
down here and add a couple printf
statements we're going to say the size
of a void pointer equals we'll do zu
because we're using memory sizes good
habit to get into and we'll do size of
void pointer and then let's do the same
thing with our int pointer so we'll do
p right here i p right here and change
this to be
an int pointer okay so now we can
compile it we can come down here and run
it and you can see that both of these
are the same size at least on my machine
we're looking at eight bytes per pointer
because they're both simply storing an
address and on my machine an address is
eight bytes and since these pointers are
basically the same we can do something
like i could say p equals ip right i can
just assign one address value to another
and just to see this in action let's
come up here and we're gonna make let's
make an integer we'll call it x and
assign it to a value let's say it's
speed beef and then i'm going to come
down here and take my in pointer and
assign it to the address of x now note
that i could have just done the same
thing with p i could say p equals the
address of x that's going to work just
fine too but let's not do that for right
now we'll come to that later my point
right now is that we have a value here
and we should have an actual address
being assigned to ip and then when we
assign p to be ip we should end up with
the same addresses so just to verify
that let's come down here and get
ourselves a another printf statement
it's going to be p
points to
percent p if you haven't seen the
percent p format specifier this is
simply
there for printing out addresses which
is exactly what i want to do right now
is i'm going to print out the address of
p and the address of ip and now if we
come down once again we compile it and
if we run it you can see we get the same
address for both pointers so i hope at
this point it's making it clear that
they're both pointers they're both
storing an address in this case they're
storing the exact same address so what's
the difference well for one one
difference is because we have type
information around it i can come in here
and i can say ip you know star iep i can
de-reference it and say this equals
something else like let's say
coffee okay so this is going to store
the integer coffee at the address that
ip points to but i'm going to run into
trouble if i try to do the same thing
like so let's say i do star p equals and
i give it its own value
if i can type beef now this is going to
give me a little bit of trouble if i
come down here and try to compile it
it's going to say hey wait a minute void
is not assignable you can't assign
something to void you have no type
information here so the first thing you
need to know about void pointers i guess
is that you can't dereference them or at
least you shouldn't de-reference them in
general because you can't do much with
void but of course this is only a minor
inconvenience because as i mentioned in
some previous videos c is not a type
safe language so we can just add a cast
in here and what i'm saying here with
this cast is i'm saying i want you to
treat p as though it were an in pointer
and then dereference it and now with
this added cast this line is now going
to work just fine so again once more
let's just double check let's make sure
that this is actually working and we'll
print out our
contents we will add a
percent x specifier because i'm going to
print out in hexadecimal and we'll come
down here and do star p
and star ip
once again i am going to need the cast
because otherwise it would complain to
me saying it doesn't know what to do
with this void pointer
and now we can come down and compile it
and if we run it you can see that both
of these memory addresses are pointing
both of these addresses are pointing to
the memory containing dead beef now
let's pause here really quickly to make
sure this all makes sense some of you
may be wondering about what happened to
coffee that i wrote up here in
the location pointed to by ip and i did
this on purpose because i wanted you to
remember that these two pointers are at
this time pointing to the same location
in memory so the last write to the
memory pointed to by p that overwrote
the previous values in that memory and
both pointers are pointing to the same
thing so they only are showing the last
thing that was written so just to
illustrate this just to try to tease
this apart let's now make them separate
so instead of assigning p to be ip right
here i'm going to take this out and
let's come up here and make another int
and y and i'm going to assign p to be
the address of y so now with just that
subtle change that very small change i
can come down here and i can run it and
now you can see that we have different
addresses and different values because
the two pointers are now pointing to two
different locations okay so that's cool
but why would we ever want to use a
pointer with no type information it just
seems like it makes more work because
you have to keep casting things and it's
just limiting right and the answer is
that basically anytime you want to store
generic memory addresses basically when
you want to store an address but you
don't really care what type it points to
so one example that you're going to see
a lot is when you use a memory allocator
so let's say instead of assigning p up
here to the address of why let's say we
come in here and say malik's size of int
so this is just saying hey i want you to
dynamically allocate on the heap a block
of memory that is integer sized and then
we're going to assign it to p and then
of course we should come down here at
the end and free p once we're done with
it and of course this would work with
our ant pointer as well but let's just
take a look before we get to all that
let's just look at the man page for
malik sorry and
malek so this is showing us the malik
and free man page we can see and of
course calicryalic and realicarray but
if you look closely here notice what
malik returns when you ask for memory
what you're doing is you're saying hey i
want a certain size block of memory
malik doesn't really care what you're
going to put in that memory it just
cares what size it is and it knows that
you're not really going to care you just
want the pointer back malik is trying to
be generic so malik returns you avoid
pointer and of course up here in our
program we could use malik with a
non-void pointer and we'll get to that
in just a minute but but first before we
finish with the man page if you look at
free similarly when free when we're done
with the memory and we're just trying to
like give it up and let somebody else
use it notice what we pass in we pass in
a void pointer again because again free
doesn't really care what types you put
in that block it just wants to reclaim
the block so just give me the address i
don't care what's actually stored there
another quick example just while we're
looking at examples is
mem copy which we looked at in a recent
video that one involved an angry
squirrel just in case you haven't
checked it out but notice again here
that mem copy is using void pointers and
the reason is it doesn't care what you
stored there it's just just give me an
address i'm going to copy the memory i
don't really care what it is i'm just
going to copy bytes so again the point
here is anytime that you're trying to
work with an address a block of memory
you want to store a pointer but you
don't care what it actually points to
then a void pointer is a really good
option this will allow you to for
example if i wanted an array of pointers
and i wanted to have them each pointing
to different things i could do that with
void pointers so but now let's just
tweak this a little bit let's get out of
here and let's come in here and tweak
things to make it work a little more how
we usually do things in our programs
because usually in a program if i knew
that i wanted to have an int here i
wouldn't have a void pointer assigned to
the result from malik instead what i
would do and let's just let's just swap
these two so we'll have p be assigned to
the address of x and we'll come down
here and we will have the integer
pointer now pointing to the or assigned
to the result from malloc and i should
come down here and free ip okay so now
at this point i do have an unused
variable we'll get rid of y really quick
and if we come down now our example
works just like it did before it doesn't
really matter we we did change up the
addresses so now ip is on the heap
rather than p is on the heap but
otherwise basically we got the same
thing but the reason i bring this up is
that this highlights a difference
between c and c plus plus that i just
want to point out so let's quickly just
take this over to c plus plus and now if
we compile it you notice that we have a
problem you see when c
saw me assign a void pointer coming from
malik to an in pointer it was like cool
people do that all the time that's what
people do with malik but when c plus
plus saw it it was like hey those aren't
the same kind of pointer do you think
they're aware of that you see c plus
plus is a bit more of a worrier so in c
plus plus we would have to come up here
and add a cast to an integer pointer and
now if we come down here it's going to
compile just fine and in case you're
wondering it will run just the same and
i just want to make it clear here that
i'm not saying that one of these
approaches the c approach of the c plus
approach is better than the other i do
wish they would agree on one common way
and do the same thing because it would
mean a little bit less for us to keep
track of in our heads but i really think
this is just a reflection of the two
languages individual personalities c
over here is going to allow you to write
slightly more concise code while c plus
plus over here is going to force you to
acknowledge when you assign a pointer of
one type to a pointer of another type
and that's not a bad thing because
that's actually the cause that's the
source of a lot of weird bugs the main
thing is to be aware of it and if you're
writing code that needs to be portable
to both c and c plus plus then just
include the cast right here that will
create more portable code because c
doesn't mind so he's happy with that
cast but c plus requires it so thanks
for looking into the void with me today
i hope you learned something new please
like subscribe go on a clicking spree
just click on everything just to let the
youtube algorithm know that there's
something interesting going on here and
until next week i'll see you later
5.0 / 5 (0 votes)