0

Basically I want to scanf "strings" from a text file and pass them through to another method (that does array stuff). The current method I have works, but because I don't know the size of the potential input, I have to allocate a ridiculous amount of memory for any sized string (repeating this free and allocating process until there are no more items to be read) Is there a more eloquent solution to what I already have?

int main(void) {
char *item;
item = emalloc(100000 * sizeof *item);
flexarray my_flexarray = flexarray_new();

while (1 == scanf("%s",item)) {
    flexarray_append(my_flexarray, item);
    free(item);
    item = emalloc(100000 * sizeof *item);
}
free(item);

flexarray_print(my_flexarray);
flexarray_free(my_flexarray);
return EXIT_SUCCESS;
}
John
  • 137
  • 10
  • What is `flexarray` and `emalloc`? Did you compile with all warnings and debug info (`gcc -Wall -Wextra -g`)? Did you use the debugger `gdb` and [valgrind](http://valgrind.org/)? – Basile Starynkevitch Sep 01 '17 at 05:16
  • 2
    This is a repeated question from *How to prevent scanf causing a buffer overflow in C?* as well: https://stackoverflow.com/questions/1621394/how-to-prevent-scanf-causing-a-buffer-overflow-in-c The answer of how to dynamically allocate memory from scanf is listed in the man page on `scanf`: *EXAMPLE To use the dynamic allocation conversion specifier, specify m as a length modifier (thus %ms or %m[range]).* – David John Coleman II Sep 01 '17 at 05:18
  • I usually use a recursive function I wrote which basically allocates reasonably-sized chunk of memory in each subcall, hitting the deepest recurse when the end of the string is found, then allocate a single buffer of the correct *total* length, then when returning upwards through each call, copy the chunk in each level into the right place in the final, longer buffer. I wouldn't do that in the kernel, and I'm used to linux hosts with logical memory disabled - so malloc actually fails when no memory's left - but I'm pretty happy with it. – Alex North-Keys Sep 04 '17 at 21:31

0 Answers0