Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C malloc a pointer multiple times

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.

like image 964
Scott.D Avatar asked Apr 09 '26 14:04

Scott.D


2 Answers

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 ptr still has the values and also tmp points 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 .

like image 132
ameyCU Avatar answered Apr 12 '26 02:04

ameyCU


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.

like image 28
Shubham Khatri Avatar answered Apr 12 '26 02:04

Shubham Khatri