LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

Why do I lose my data when I use realloc() to increase the size of the array ?

Problem: My data is not moved to the new memory block created by realloc(). As I read my streaming data from a file or serial port. I want to store a part of the data in a dynamic array of doubles, to be graphed on a strip chart real time. When I use realloc() to increase the size by one "double", to make room for the next data item, the array size is increased, but the old data is not moved to the new block of memory, and is lost !
Since I dont know the number of doubles that are to be read, I want to use realloc() to increase the size as I get new data. My solution was to copy the data to a temporary malloc() array, then use realloc() to increase the size, then copy the data back. I sho
uld not have to do this. should I ? Realloc() should move the existing data in the array to the new block of memory, and give me room for my new data ?
0 Kudos
Message 1 of 2
(15,478 Views)
realloc should preserve the previous data if the pointer supplied in the call is a valid pointer to the memory region previously allocated and the new size is larger than the previously allocated size. If the pointer supplied in the realloc call is null, then it acts just like a malloc. Note that in fulfilling your realloc request, the previous data may get moved into a new, larger area. Any pointers you've established into the array would be invalidated after the realloc call in that case. You should reference your array with subscript expressions instead of pointers to avoid this problem.

You can see if the realloc call is causing your previous data to be moved by comparing the pointer value before and after the call. If the pointer value's changed, then
all of your previous data was copied to a new, larger memory area.

See page 388 of "C, A Reference Manual" 4th Edition by Harbison & Steele, ISBN 0-13-326224-3 for an explanation and an example of using a dynamic array of doubles with the realloc function.
Message 2 of 2
(15,478 Views)