0

I'm using reallocto 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.

PlayHardGoPro
  • 2,791
  • 10
  • 51
  • 90
  • The code you've posted looks OK. There is probably already heap corruption due to another bug in your program. To get better help, [follow the instructions to create a MCVE](http://stackoverflow.com/help/mcve) – M.M Mar 20 '15 at 00:03
  • @MattMcNabb Thanks. What about my thought, is it right? If I reallocate from 10 slots to 9 will I lose only the last one ? The rest of the data will be ok allocated? – PlayHardGoPro Mar 20 '15 at 00:06
  • 1
    Yes that's how it works. – M.M Mar 20 '15 at 00:15
  • 1
    Indeed! I've just tested it with a simple struct with only an integer field, and `realloc` works as expected (although it didn't really change the buffer address which I find logical). – mcleod_ideafix Mar 20 '15 at 00:21
  • @mcleod_ideafix SO after all I have to `free(buffer)` right? – PlayHardGoPro Mar 20 '15 at 00:22
  • 1
    As `buffer` and `struc` point to the same memory region (remember, you just made `struc = buffer`) you can free any of them. – mcleod_ideafix Mar 20 '15 at 01:31

1 Answers1

1

Your data can be moved by realloc(). So if there is any pointer to the data, after the call, such pointers would become invalid.

AntoineL
  • 888
  • 4
  • 25
  • So after `realloc` I cant access: `my_struct[0].Name` is there was already data on it? Is there a solution for that? Do I have to call a function to fill it again ? – PlayHardGoPro Mar 20 '15 at 00:08
  • 1
    @PlayHardGoPro did you mean `struc[0].Name`? Yes you can access that. What you can't do is `my_struct *ptr = &struc[0]; ` , then your realloc code, then access `ptr->Name`. – M.M Mar 20 '15 at 00:15
  • Got the error. Thank you sir! I wrote it right but the original code I was using the wrong parameter for realloc. ;s – PlayHardGoPro Mar 20 '15 at 00:17