Created
December 11, 2012 20:37
-
-
Save joequery/4261932 to your computer and use it in GitHub Desktop.
Safely using getenv with snprintf in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdlib.h> | |
| #include <stdio.h> | |
| #define BUFSIZE 80 | |
| int main(){ | |
| char *cwd1; | |
| char cwd2[BUFSIZE]; | |
| int result; | |
| // Get the current working directory. This is vulnerable to buffer | |
| // overflows! | |
| cwd1 = getenv("PWD"); | |
| printf("cwd1: %s\n", cwd1); | |
| // We use snprintf to prevent buffer overflows. According to the man pages, | |
| // if the return value of snprintf is >= BUFSIZE, the string was truncated, | |
| // indicating the buffer was not big enough. Resize BUFSIZE to something | |
| // extremely small to watch this in action. | |
| result = snprintf(cwd2, BUFSIZE, "%s", getenv("PWD")); | |
| if(result >= BUFSIZE){ | |
| fprintf(stderr, "BUFSIZE of %d was too small. Aborting\n", BUFSIZE); | |
| exit(1); | |
| } | |
| printf("cwd2: %s\n", cwd2); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment