Use% (limit) [^ \ n] in scanf is it safe to capture strings?

2

I'd like to know a totally secure way of capturing strings without running buffer overflow or any other threat.

I read a lot about ready-made functions and would like to know which are the most recommended, but I wanted to be able to implement one and know how the thing really works.

So far, I have found it useful to use %(limite)[^\n] to capture an entry until the user hits enter or reaches a number (limit) of characters read. For this case, if the user continues typing it will fill in the buffer (right?), So I will have to clear the buffer for the next read (right?). / p>     

asked by anonymous 07.11.2014 / 14:01

1 answer

2

The ideal would be to use the fgets function:

fgets(buffer, buffer_size, stdin);

But you can not limit yourself to it, as you can see below:

Max string length using scanf - > ANSI C

How to use sscanf correctly and safely

How to prevent scanf causing a buffer overflow in C?

My guess about the implementation would be to loop between 0 and the buffer size, and within that loop use getchar() :

char str[100];
size_t buffer_size = 100;
size_t i = 0;
while(i < buffer_size-1 && (str[i] = getchar()) != '\n')
  ++i; 
str[i] = '
fgets(buffer, buffer_size, stdin);
';

(If I needed it, I would implement it as above)

How it's implemented: Official implementation ( BSD)

    
09.11.2014 / 00:18