LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   reading a char string of variable size in C (https://www.linuxquestions.org/questions/programming-9/reading-a-char-string-of-variable-size-in-c-321330/)

introuble 05-08-2005 11:39 AM

reading a char string of variable size in C
 
ok .. so we want to read a char string of a variable size ..

int BUF_SIZE;
char *buf;

we first get the BUF_SIZE:

scanf("%d", &BUF_SIZE);

we make room for the buffer:

buf = (char*) malloc(BUF_SIZE);

.. this gives segmentation fault:

fscanf(stdin, "%s", buf);

.. what is the correct way to read the char string into buf ?

btmiller 05-08-2005 12:30 PM

A couple points:

(1) don't cast the return value of malloc. This can mask subtle coding errors if you forget to include stdlib.h

(2) fscanf(stdin, "%s", buf); is classic insecure (prone to buffer overflow exploit) code. What if the user enters more than BUF_SIZE data?

You can use the GNU readline function if you're writing GNU code, otherwise, it's not terribly tough to hack together your own readline lib (I did it awhile ago). Basically malloc a buffer of a certain size and then read one character at a time from input. Keep track of how many characters you read. When you're running low on space, realloc the buffer to a larger size. You may want to set some global maximum buffer size to prevent out of control usage. Also don't forget the terminator at the end of the string!

introuble 05-08-2005 12:35 PM

hm.. I was under the impression that fscanf was secure .. so the only way to read a char string securely is to implement your own "readline" (or use the FSF readline ...) ?

since we are .. "in topic" .. is there any "list" with insecure functions/common security mistakes in C programming ? (the more technically detailed the better)

btmiller 05-08-2005 01:07 PM

You can make scanf and friends more secure by not allowing arbitrary length strings as input. For instance scanf("%10s", buffer) will only read 10 characters at most in. You do need to pick the number at compile time though. You can also use fgets which allows you to specify a maximum size. But you can't expand that size if you get more data than you expect, so you wind up implementing a readline-like library if you care about getting everything.

I'm not sure about a list like you describe, but there's lots of good info in the comp.lang.c FAQ.


All times are GMT -5. The time now is 02:19 AM.