Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion about realloc function

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?

like image 594
Jayesh Avatar asked Dec 11 '22 09:12

Jayesh


2 Answers

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.

like image 59
StoryTeller - Unslander Monica Avatar answered Jan 02 '23 15:01

StoryTeller - Unslander Monica


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

like image 36
alinsoar Avatar answered Jan 02 '23 16:01

alinsoar