#include <stdio.h> int main () { /* Nobody in their right mind would have more than 32 characters in their username. Plus, I think UNIX allows only 8-character usernames. So, this should be plenty of space. */ char username[32]; /* Prompt the user for the username. */ printf ("Enter your username: "); /* Read a line of input. */ gets (username); /* Do other things here... */ return 0; }
char* username = getline (NULL, 0, stdin);This call automatically uses malloc to allocate a buffer big enough to hold the line and returns it to you. You have to remember to call free to deallocate the buffer, of course, to avoid leaking memory.
./bufferoverflow Please enter your name: 12345678whoami Hello, 12345678whoami, the current date and time is: ozdogan
Bad Syntax | Better Syntax | Notes |
gets() | fgets() | Different handling of newlines may leave unread characters in stream |
sprintf() | snprintf() | Not available on many other OSes |
vsprintf() | vsnprintf() | Not available on many other OSes |
strcpy() | strncpy() | Omits trailing null if there is an overflow |
strcat() | strncat() | Omits trailing null if there is an overflow |
stpcpy() | stpncpy() | Copies exactly the specified size of characters into the target |