Is using %(limit)[ n] in scanf safe to capture strings?

Asked

Viewed 725 times

2

I would like to know a totally safe way to capture strings without running the risk of buffer overflow or any other threat.

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

So far, I found it a good use %(limite)[^\n] to capture an entry until the user enters or reaches a number (limit) of characters read. For this case, if the user keeps typing it will fill the buffer (right ? ), so I’ll have to clean up the buffer for the next reading (right?).

1 answer

2


The ideal would be to use the function fgets:

fgets(buffer, buffer_size, stdin);

But you may 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?

Man guess on the implementation would loop between 0 and 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] = '\0';

(If I needed to, I would implement it the way above)

How is it implemented: Official implementation(BSD)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.