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:
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;
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;
}
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