Understanding malloc
I was given this piece of example code on a lab and I'm trying to understand it
int size = 5;
int **ppi2 = (int **) malloc(size * sizeof(int *));
Here's my breakdown of it as of now:
In order to allocate sufficient memory, we must multiply the number of things we want to allocate memory for (size) by the size of those things (sizeof(int *)). That much is straightforward and makes a lot of sense.
I understand that we have to cast the result of malloc into a double pointer, since malloc returns bytes and the variable is a double pointer, but why are we setting ppi2 equal to the result of malloc in the first place? Does it make ppi2 point to the spot in memory that we just allocated?
With malloc, you pass as a parameter the number of bytes of memory you want to allocate and it returns the address to the beginning of the memory you just allocated. With that address stored in a pointer, you can then do what you must with it. It does not return the bytes of memory, it returns the address so you can then go and manipulate them. That's why C memory management is important to grasp (you somehow lose that address, you "lose" the memory).
If you want to get a better understanding of how malloc
works with the memory and its relationship with your program (which I recommend since its fundamental knowledge), read Chapter 13 of the Three Easy Pieces operative system book. It's short, it's awesome.
I understand that we have to cast the result of malloc into a double pointer, since malloc returns bytes and the variable is a double pointer...
Do not cast the return value of malloc
.
why are we setting ppi2 equal to the result of malloc in the first place?
To point to the same location as by the pointer return by the malloc
.
Does it make ppi2 point to the spot in memory that we just allocated?
Yes.
I understand that we have to cast the result of malloc into a double pointer, since malloc returns bytes and the variable is a double pointer,
malloc doesn't return the bytes; it returns a pointer that points into the bytes it allocates. This pointer has a generic pointer type void *
. In C++ you must cast this void *
back into the pointer type of your variable but in plain C this cast is optional.
but why are we setting ppi2 equal to the result of malloc in the first place? Does it make ppi2 point to the spot in memory that we just allocated?
Yes.
链接地址: http://www.djcxy.com/p/28462.html上一篇: malloc分配给指针
下一篇: 了解malloc