Reputation: 7
I have this simple code snippet as seen below:
#include <stdio.h>
#include <stdlib.h>
int main() {
int size;
int *a, *a2;
size = 5;
a = malloc(size * sizeof(int));
if(a == NULL) {
fprintf(stderr, "Failure at allocating memory for array.\n");
abort();
}
for(int i = 0; i < size; i++) {
a[i] = i * i;
printf("Array %d element: %d.\n", i, a[i]);
}
size = 2;
a2 = realloc(a, size * sizeof(int));
if(a2 == NULL) {
free(a);
fprintf(stderr, "Failure at reallocating memory for array.\n");
abort();
}
printf("\n");
size = 5;
for(int i = 0; i < size; i++) {
a2[i] = i * i * i;
printf("Array %d element after realloc: %d.\n", i, a2[i]);
}
free(a2);
return 0;
}
Realloc doesn't actually shrink the array to 2 elements, instead all initial 5 allocated elements are accessed normally, as seen in the output:
Array 0 element: 0.
Array 1 element: 1.
Array 2 element: 4.
Array 3 element: 9.
Array 4 element: 16.
Array 0 element after realloc: 0.
Array 1 element after realloc: 1.
Array 2 element after realloc: 8.
Array 3 element after realloc: 27.
Array 4 element after realloc: 64.
Is this behavior normal? Did I do something wrong?
Upvotes: 0
Views: 92
Reputation: 224842
Once you shrink the allocated memory from 5*sizeof(int)
to 2*sizeof(int)
, the allocated space is only large enough to hold 2 objects of type int
. Attempting to access past that point triggers undefined behavior in your code.
That it happened to work in your case is by no means guaranteed and should not be depended on.
Upvotes: 3