Skip to content

Instantly share code, notes, and snippets.

@alexwebr
Last active May 11, 2016 16:41
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 alexwebr/44a056f38ea30441dcb8842d0ab11c8d to your computer and use it in GitHub Desktop.
Save alexwebr/44a056f38ea30441dcb8842d0ab11c8d to your computer and use it in GitHub Desktop.
Bad use of strncpy()
#include <string.h>
#include <stdio.h>
#include <assert.h>
// Find this with:
// git grep 'strncpy(\([^,]\+\), [^,]\+, sizeof(\1));'
int main(int argc, char *argv[])
{
// Take a single string argument
if (argc < 2)
return 1;
struct {
char a[20];
char b[20];
} data;
/**
* Check that there isn't any padding between the end of 'a' and the
* beginning of 'b'.
*
* Add 'struct __attribute__((packed)) { ...' if this assert fails.
**/
assert(sizeof(data) == sizeof(data.a) + sizeof(data.b));
// Zero the structure, which also will make sure all the strings are
// full of NUL bytes.
bzero(&data, sizeof(data));
// Initialize the second member
strcpy(data.b, "yellow submarine");
// *Incorrectly* use strncpy
strncpy(data.a, argv[1], sizeof(data.a));
// May echo the first argument, or also "yellow submarine"!
puts(data.a);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment