Last active
May 11, 2016 16:41
-
-
Save alexwebr/44a056f38ea30441dcb8842d0ab11c8d to your computer and use it in GitHub Desktop.
Bad use of strncpy()
This file contains 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 <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