I read about dynamic memory allocation in C using this reference.
That document Say's :
realloc() should only be used for dynamically allocated memory. If the memory is not dynamically allocated, then behavior is undefined.
If we use realloc()
something like this:
int main()
{
int *ptr;
int *ptr_new = (int *)realloc(ptr, sizeof(int));
return 0;
}
According to that reference, this program is undefined because pointer ptr not allocated dynamically.
But, If I use something like:
int main()
{
int *ptr = NULL;
int *ptr_new = (int *)realloc(ptr, sizeof(int));
return 0;
}
Is it also undefined behavior according to that reference?
I thing second case does not invoked undefined behaviour. Am I right?
The first case has undefined behavior, and the second doesn't. In the first case, the value of ptr
is indeterminate. So passing that value to realloc
or any function, is undefined by itself.
On the other hand, since realloc
has well defined behavior when passed a null pointer value (it's just like calling malloc
)1, the second piece of code is perfectly legitimate (other than the fact you don't free
anything).
17.22.3.5 The realloc function / p3
If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size.
In the first case the program almost sure will finish by segmentation fault
as the linked lists that are created in the heap to find segments are not coherent, in the second case you call the realloc with the NULL first parameter, which means, is a call equivalent to malloc(size)
man realloc
says:
void *malloc(size_t size);
void *realloc(void *ptr, size_t size);
If ptr is NULL, then the call is equivalent to malloc(size), for all values of size
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