K
Kamus of Kadizhar
I have a question that's probably not uncommon.
I am reading a number of short strings from a file. Each string gets put
in the next element of an array. I have no idea how many of these strings
there are; I do know they are all short (< 8 bytes). There could be a
handful or as many as a couple of hundred, so we're not talking great
amounts. I don't have any control over how many there will be;
conceivably some dedicated (or misinformed) user could throw in thousands.
What's the best way to allocate memory for this?
Basically, the code is something like this (untested code):
char **keymap;
while( fscanf(fp,"%4095s ",lineBuffer) == 1 ) {
... some validation ...
if( sscanf(lineBuffer,"%7s ",charBuffer) == 1) {
/* we potentially have a keymap */
if( !g_utf8_validate(charBuffer) ) {
/* it's not a valid UTF-8 string */
printf("malformed line >%s< ",charBuffer);
return FALSE;
}
/* now we need to allocate the next element of keymap
* and assign the contents of charBuffer
*/
???????????????????
}
}
I can malloc() each element, but how do I expand the size of keymap?
realloc every time? That seems very wasteful.
--Kamus
I am reading a number of short strings from a file. Each string gets put
in the next element of an array. I have no idea how many of these strings
there are; I do know they are all short (< 8 bytes). There could be a
handful or as many as a couple of hundred, so we're not talking great
amounts. I don't have any control over how many there will be;
conceivably some dedicated (or misinformed) user could throw in thousands.
What's the best way to allocate memory for this?
Basically, the code is something like this (untested code):
char **keymap;
while( fscanf(fp,"%4095s ",lineBuffer) == 1 ) {
... some validation ...
if( sscanf(lineBuffer,"%7s ",charBuffer) == 1) {
/* we potentially have a keymap */
if( !g_utf8_validate(charBuffer) ) {
/* it's not a valid UTF-8 string */
printf("malformed line >%s< ",charBuffer);
return FALSE;
}
/* now we need to allocate the next element of keymap
* and assign the contents of charBuffer
*/
???????????????????
}
}
I can malloc() each element, but how do I expand the size of keymap?
realloc every time? That seems very wasteful.
--Kamus