Hi,
I have a (C) program which reads a stream of characters from a file into an array of data, currently structured as
char data[num][len];
where num is relatively small (< 100) and len relatively large (up to 20000). Both num and len can vary from file to file. I want to optimize the code using dynamic memory allocation. The data in the file is formatted something like:
...
data[0] header
len_1 of chars
data[1] header
len_2 of chars
...
data[n] header
len_n of chars
Making dynamically allocated structures for each 'num' is easy, but I don't know how long each 'len' is until it is read. One obvious implementation is to use malloc to create the 1st char of data[0] and then realloc for each additional char, but this seems inefficient and potentially slow to me.
The other solution may be to malloc a block (1000?) of chars, read until it's full, realloc another block if needed, and so on, then free any leftover space in the last block at the end. Is this approach efficient or does someone have a better recommendation?
jimdgar
Start Free Trial