Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if I use malloc twice on the same pointer (C)?

Tags:

Say for instance I created a pointer newPtr and I use malloc(some size) and then later I use malloc(some size) again with the same pointer. What happens? Am i then creating a second block of memory the same size of the first one? Does newPtr point to the same address?

Example:

int *newPtr; newPtr = malloc(10 * sizeof(int)); newPtr = malloc(10 * sizeof(int)); 
like image 538
Ace Avatar asked Oct 17 '13 19:10

Ace


People also ask

Can we use multiple malloc () instead of realloc ()?

malloc is not required, you can use realloc only. malloc(n) is equivalent to realloc(NULL, n) . However, it is often clearer to use malloc instead of special semantics of realloc . It's not a matter of what works, but not confusing people reading the code.

What happens when you use malloc?

malloc() allocates memory of a requested size and returns a pointer to the beginning of the allocated block.

What will happen if you malloc and free instead of delete?

If we allocate memory using malloc, it should be deleted using free. If we allocate memory using new, it should be deleted using delete. Now, in order to check what happens if we do the reverse, I wrote a small code.

What happens if you don't free after malloc?

If free() is not used in a program the memory allocated using malloc() will be de-allocated after completion of the execution of the program (included program execution time is relatively small and the program ends normally).


1 Answers

Your program will have a memory leak. The first value of newPtr will be lost and you will not be able to free it.

Am i then creating a second block of memory the same size of the first one?

Yes. You are allocating a second object, distinct from the first one.

Does newPtr point to the same address?

No. The objects are distinct, so their address are distinct.

like image 70
ouah Avatar answered Sep 19 '22 07:09

ouah