Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I enforce realloc check if the new block size is smaller than the initial?

Tags:

c

realloc

Can realloc fail in this case?

int *a = NULL;

a = calloc(100, sizeof(*a));
printf("1.ptr: %d\n", a);

a = realloc(a, 50 * sizeof(*a));
printf("2.ptr: %d\n", a);

if(a == NULL){
    printf("Is it possible?\n");
}

return (0);

}

The output in my case is:

1.ptr: 4072560
2.ptr: 4072560

So 'a' points to the same adress. So should I enforce realloc check?

Later edit:

  • Using MinGW compiler under Windows XP.
  • Is the behaviour similar with gcc on Linux ?

Later edit 2: Is it OK to check this way ?

int *a = NULL, *b = NULL;

a = calloc(100, sizeof(*a));
b = realloc(a, 50 * sizeof(*a));

if(b == NULL){
    return a;
}
a = b;
return a;
like image 836
Andrei Ciobanu Avatar asked Mar 29 '10 20:03

Andrei Ciobanu


1 Answers

Yes, you should always enforce a check on realloc, or any other memory allocation for that matter.

The current behavior of re-using the same address is an implementation detail that should not be relied upon. Doing so is just opening yourself up for bugs when either the library switches it's implementation or you move to a new platform.

Is it likely this will ever fail? Probably not, I'd be astounded if you could find a case that it does. However that doesn't mean it won't. Wrapping realloc in a function which automatically does the check for every operation is simple enough that there's no reason to not do it.

void* xrealloc(void* ptr, size_t size) {
  ptr = realloc(ptr, size);
  if ( !ptr ) {
    exit(EXIT_FAILURE);
  }
  return ptr;
}
like image 140
JaredPar Avatar answered Oct 24 '22 18:10

JaredPar