Sign in to follow this  
godmodder

Reading variable size strings in C without buffer overflows

Recommended Posts

godmodder    828
Hello, What would be the most elegant way to handle variable size input strings from the user in pure C, without the possibility of a buffer overflow? So far I thought of two ways, but they don't handle a string of any size, they just minimize the danger of a buffer overflow: 1) char buffer[512]; scanf("%512s", buffer); 2) char buffer[512]; fgets(buffer, 512, stdin); This works nicely, but the user can still type in more than the buffer can contain. How can I make it totally dynamic? (Pure C, no C++, other libraries,...) Thanks in advance, Jeroen

Share this post


Link to post
Share on other sites
SiCrane    11839
You'll need to use dynamic memory. Allocate with malloc(). Read data into your buffer, up to the size of the buffer. If there's more input resize the buffer with realloc(). Repeat until you're out of input or out of memory.

Share this post


Link to post
Share on other sites
Evil Steve    2017
There's nothing stopping you malloc()ing a new chunk of memory, copying the contents from the old chunk into the new chunk, and then free()ing the old chunk.

Of course there's no reason to with realloc(), I just mean if you didn't know about realloc(). In fact, realloc() will just do that internally (It'll try to expand the memory block rather than reallocate it where possible though).

Share this post


Link to post
Share on other sites
Rydinare    487
A sneaky way is to write C++ code that use an STL string internally (thus totally safe) and just extern "C" the functions so that they can be used from C. [smile]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this