0

When I call realloc on a pointer to reduce its size what does it happen? For example, let's considering this:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int* a = malloc(4*sizeof(int));
    a[0]= 1;
    a[1]= 1;
    a[2]= 1;
    a[3]= 1;
    
    int* temp = realloc(a, 3* sizeof(int));
    if(!temp)
        exit(1);
    a = temp;
    a[3] = 10;
    return 0;
}

I expect that when I call a = realloc(a, 3* sizeof(int)); it will throw SIGSEGV, but it doesn't.

  • 1
    `realloc` can't set it to NULL, because it is passed by value. – Eugene Sh. Feb 14 '23 at 14:30
  • 1
    A segmentation fault is always a manifestation of **undefined behavior**. Therefore, the C language specifications never provide any basis for expecting a segfault (if they did, that would be *defined* behavior). In practice, most C implementations do not proactively guard against bounds overruns, so you cannot assume that overruns will be detected, much less that any particular behavior will follow from one. – John Bollinger Feb 14 '23 at 14:31

0 Answers0