Skip to content

Instantly share code, notes, and snippets.

@kees
Created June 26, 2015 17:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kees/e561143ba0bd0ca163bc to your computer and use it in GitHub Desktop.
Save kees/e561143ba0bd0ca163bc to your computer and use it in GitHub Desktop.
Show gcc's behavior regarding string literals and -Wformat-security.
/*
* Show gcc's behavior regarding string literals and -Wformat-security.
*
* gcc -Wformat -Wformat-security -Wall -Werror -o strings strings.c
*
* GPLv2+ Kees Cook <keescook@chromium.org>
*/
#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