Archived

This topic is now archived and is closed to further replies.

Malloc() problem

This topic is 5145 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Heres my problem: I''m trying to dynamicly allocate memory in a loop, according to how much data is available. Know what I mean? The situation is: I dont know how much data I''ll have to read into a char* buffer, like it could be 1K or 45megs. Perhaps an example: --------------------------------------------------- char * buffer; int bytesread; int totalbytesread; int bytestoread; bytestoread=GetNumberOfBytesToRead(); while (bytestoread>0) { buffer=(char *) malloc(bytestoread); <<--PROBLEM LINE bytesread=ReadInBytes(buffer); totalbytesread += bytesread; bytestoread=GetBytes(); } ---------------------------------------------------- thats just a rough example, however my problem lies in the malloc() statement. if the above example were executed, the data would always be written into the beginning of the buffer. However I want it to allocate more memory, at the end of the buffer, to extend it, so that the new bytes are appended to the buffer, filling up the space allocated by the last malloc() statement. I home Ive explained this clearly. Basically I need to alter the malloc statement so it will do that. Can anyone tell me how to do this?

Share this post


Link to post
Share on other sites
Sorry, heres a better version of the program:
---------------------------------------------------
char * buffer;
int bytesread;
int totalbytesread;
int bytestoread;

bytestoread=GetNumberOfBytesToRead();
while (bytestoread>0)
{
buffer=(char *) malloc(bytestoread); <<--PROBLEM LINE
bytesread=ReadInBytes(buffer);
totalbytesread += bytesread;
bytestoread=GetNumberOfBytesToRead();
}
----------------------------------------------------

Share this post


Link to post
Share on other sites