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));
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.
malloc() allocates memory of a requested size and returns a pointer to the beginning of the allocated block.
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.
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).
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.
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