Confusion about realloc function

I read about dynamic memory allocation in C using this link.

This document will say:

realloc () should only be used for dynamically allocated memory. If the memory is not allocated dynamically, then the 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 this link, this program is undefined because the ptr pointer is 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 this also undefined behavior according to this link?

In this case, the second case does not cause undefined behavior. I'm right?

+4
source share
4 answers

undefined, - . ptr . , realloc , undefined .

, realloc ( malloc) 1 ( , free ).


1 7.22.3.5 realloc/p3

ptr , realloc malloc .

+10

segmentation fault, , , , realloc NULL, , malloc(size)

man realloc :

   void *malloc(size_t size); 
   void *realloc(void *ptr, size_t size);

ptr NULL, malloc ()

+1

- . n1570 ( C11) :

§7.22.3.5 realloc, p3:

ptr - , realloc malloc . , ptr , free realloc, undefined. [...]

, .

+1
  • - , , undefined, , ptr ptr. c standard , 7.20.3.4.2 realloc

realloc , ptr , .

, - undefined.

  1. In the second case, the compiler knows what ptr is , but it realloc() will act as malloc()in accordance with 7.20.3.4.3 The realloc function

If ptr is a null pointer, the realloc function behaves like malloc for the specified size.

+1
source

Source: https://habr.com/ru/post/1689200/


All Articles