Created
June 26, 2015 17:46
-
-
Save kees/e561143ba0bd0ca163bc to your computer and use it in GitHub Desktop.
Show gcc's behavior regarding string literals and -Wformat-security.
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
/* | |
* Show gcc's behavior regarding string literals and -Wformat-security. | |
* | |
* gcc -Wformat -Wformat-security -Wall -Werror -o strings strings.c | |
* | |
* GPLv2+ Kees Cook <[email protected]> | |
*/ | |
#include <stdio.h> | |
struct structure { | |
int thing; | |
const char *name; | |
}; | |
struct cstructure { | |
int thing; | |
const char name[128]; | |
}; | |
int main(void) | |
{ | |
char array[] = "This is a char array\n"; | |
const char carray[] = "This is a const char array\n"; | |
const char cnarray[64] = "This is a sized const char array\n"; | |
char *ptr = "This is a char pointer\n"; | |
const char *cptr = "This is a const char pointer\n"; | |
const char const *ccptr = "This is a const char const pointer\n"; | |
struct structure instance[] = { | |
[0] = { 1, "This is a structure\n" }, | |
}; | |
const struct structure cinstance[] = { | |
[0] = { 1, "This is a const structure\n" }, | |
}; | |
struct cstructure instancec[] = { | |
[0] = { 1, "This is a structure with const char\n" }, | |
}; | |
const struct cstructure cinstancec[] = { | |
[0] = { 1, "This is a const structure with const char\n" }, | |
}; | |
/* These correctly do not warn. */ | |
printf("This is a literal char array\n"); // safe | |
printf(carray); // safe | |
printf(cnarray); // safe | |
/* These correctly warn. */ | |
printf(array); // unsafe | |
printf(ptr); // unsafe | |
printf(instance[0].name); // unsafe | |
printf(instancec[0].name); // unsafe | |
/* These should not warn. */ | |
printf(cptr); // should be safe | |
printf(ccptr); // should be safe | |
printf(cinstance[0].name); // should be safe | |
printf(cinstancec[0].name); // should be safe | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment