Discussions
Categories
Groups
Advertisement
Child Item
Home
Topics
Technology & Internet
Software & Web Development
Development
realloc() problems in C
Webmonkey
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.
Find more posts tagged with
Quick Links
All Categories
Recent Posts
Activity
Unanswered
Groups
Best Of
Advertisement
Advertisement
Comments
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.
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!