Malloc() problem
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?
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();
}
----------------------------------------------------
---------------------------------------------------
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();
}
----------------------------------------------------
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement