Skip to content

Instantly share code, notes, and snippets.

@alexwebr
Last active May 11, 2016
Embed
What would you like to do?
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