
Originally Posted by
raczzoli
Should I allocate the memory before I pass the variable to the function
I find it easier not to do so, because if you use that function a lot (eg, a "slurp text file" function), you will have to do this all the time:
Code:
char *data = malloc(bufsz);
slurpTextFile(path, data, bufsz);
Whereas if you make the allocation internal:
Code:
char *data = slurpTextFile(path);
Yes, use a loop like:
Code:
#define CHUNK_SZ 1024
int total, cur, chunks, check;
char *data = malloc(CHUNK_SZ+1), *test;
[ ...error check *data...]
cur = total = 0;
chunks = 1;
while ((check = read(fd, &data[total], CHUNK_SZ - cur)) {
if (check == -1) [ ...handle error...]
total += check;
if (check < CHUNK_SZ) {
// possible partial read, so try once more...
cur += check;
continue;
}
chunks++;
cur = 0;
test = realloc(data, chunks*CHUNK_SZ+1);
if (!test) {
free(data); // give mem back to system
[...return error...]
}
data = test;
}
data[total] = '\0';
return data;
So that reads data into a 1kB buffer. If that is not enough, we add another 1kB via realloc and so on. Another algorithm for this is to multiply the buffer size by 2 each time, starting fairly small. The first (linear) version is better when you know the amount of data is always going to be in a certain range. The second (power of two) version is better when the amount of data can vary from tiny to huge.
For binary data, you can do without adding the null terminator at the end and the extra byte to hold it in the allocation (and probably use an unsigned char* for the buffer).