Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

realloc() problems in C

Options
  • 02-01-2007 5:14pm
    #1
    Registered Users Posts: 9,579 ✭✭✭


    Hi There,

    I've got a program that uses Dynamic Arrays using Malloc and Realloc.
    My program has 3 array pointers having stucts as their datatypes.
    For example: struct1 * array1, struct2 * array2, struct3 * array3.

    Now I read data in from a file , each line contains one element of the struct array so i count number of lines, multiply by the sizeof(structn) and then allocate this amount of memory with malloc and then begin reading in the data.

    This works perfect for all 3 arrays.
    Next I have an option to add a new element onto each array. This is where problem arises.
    I use realloc to add on an extra sizeof(structn) memory space and increment the array size int. Now when I do this to the first array, realloc somehow goes into the allocated space of array2 and begins overwriting the start of this.

    This screws the whole program up.

    Sorry that I don't have any code example, its not on this machine and its abit long to post to be honest but I hope someone gets the idea what is happening.

    I've error checking all over too and no errors show up for Realloc and Malloc, using temporary pointers as well for realloc incase it fails and causes memory leaks.

    Hope someone can help, its driving me insane!

    Thanks.


Comments

  • Closed Accounts Posts: 4,943 ✭✭✭Mutant_Fruit


    Well, this may sound crazy, but have you tried allocating (NumberOfLines+1) *size(struct) amount of bytes? That should give you the 1 extra you need.

    If you need to really be dynamic and actually resize to array to allow N number of extra elements, we're going to need to see some code.


  • Registered Users Posts: 9,579 ✭✭✭Webmonkey


    Hey ,

    Just sorted it myself, When reallocating I didn't add one one to the size. Just as you've pointed out there Mutant, so not so crazy at all!
    My thinking was that the array size, was always one greater than the last index so this kinda threw me off when programming it as I had it in my mind that the arraysize/num of lines was big enough but obviously not.

    Stupid me!

    Thanks!


Advertisement