If I have a pointer: char ** tmp = (char **)malloc(sizeof(char *) * MAX_SIZE),
after assigning values to each block, I have a new pointer char ** ptr = tmp.
1). Can I tmp = (char **)malloc(sizeof(char *) * MAX_SIZE) malloc it again without free it?
2). Does the ptr still has the values and also tmp points to a new block of memory?
I have a function to free all used memory at the end, so don't worry about free.
1). Can I
tmp = (char **)malloc(sizeof(char *) * MAX_SIZE)malloc it again without free it?
Yes , you can again allocate memory again . But tmp will now point to a new allocated memory and to previously allocated memory .
2). Does the
ptrstill has the values and alsotmppoints to a new block of memory?
Now tmp will point to newly allocated memory but ptr refers to the previous memory location which was allocated .
So in this way you don't loose reference to any of the memory block and can be freed .
malloc is used to allocate a memory block. It allocates a block of memory of provided size and return a pointer to the beginning of the block.
So the first time you write
char ** tmp = (char **)malloc(sizeof(char *) * MAX_SIZE)
it allocates memory and return a pointer pointing to beginning of memory location to temp. Now when you assign tmp to ptr, ptr now points to the allocated memory along with tmp. Now again if you write tmp = (char **)malloc(sizeof(char *) * MAX_SIZE) it will allocate a new memory and return a pointer to which tmp will be pointing to. But ptr still continues to point to the previously allocated memory. So the answer to both of your question is YES.
I hope I was able to explain the things correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With