I'm using realloc
to reduce the size of my vector. I want to loose the last position only. so, if I have 10 positions and I use realloc
to allocate enough space for 9 * sizeof(my_struct)
will the vector get truncated and keep the old data but the last position ? I thought it was right, but when I try to print the value after the realloc I get Segmentation Fault
error. Here is my code:
//Instanciate the vector
my_struct *struc;
my_struct *buffer;
//Allocate space for 10 slots
struc = (my_struct *) malloc(10 * sizeof(my_struct));
//realloc for 9 slots
buffer = (my_struct *) realloc(struc, 9 * sizeof(my_struct));
if(buffer != NULL){
struc = buffer;
}
now if I try to use printf
to check the elements inside the vector, I get Segmentaition Fault
OBS: The Vector has been filled up with data BEFORE the realloc. I didnt post here because I think it's unnecessary... Imagine the vector already with data in this code.
Your data can be moved by realloc()
. So if there is any pointer to the data, after the call, such pointers would become invalid.