Jump to content
  • Advertisement
Sign in to follow this  
godmodder

Reading variable size strings in C without buffer overflows

This topic is 3775 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
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
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
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!