Created
January 17, 2021 20:30
-
-
Save zcsahok/8706fab5dfc16641ddbc2b70f6b39b8f to your computer and use it in GitHub Desktop.
strncpy test
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
#include <stdio.h> | |
#include <string.h> | |
/* | |
output: | |
w's: 77 77 77 77 | |
short1: 61 77 77 77 | |
short2: 61 62 77 77 | |
short3: 61 62 00 77 | |
long1: 61 77 77 77 | |
long2: 61 62 77 77 | |
long3: 61 62 63 77 | |
long4: 61 62 63 64 | |
*/ | |
char dest[4]; | |
char src[10]; | |
void dump_dest(const char *info) { | |
printf("%10s:", info); | |
for(int i = 0; i < 4; ++i) { | |
printf(" %02x", dest[i]); | |
} | |
printf("\n"); | |
} | |
int main() { | |
memset(dest, 'w', sizeof(dest)); | |
dump_dest("w's"); | |
strcpy(src, "ab"); // src is shorter | |
memset(dest, 'w', sizeof(dest)); | |
strncpy(dest, src, 1); | |
dump_dest("short1"); | |
memset(dest, 'w', sizeof(dest)); | |
strncpy(dest, src, 2); | |
dump_dest("short2"); | |
memset(dest, 'w', sizeof(dest)); | |
strncpy(dest, src, 3); | |
dump_dest("short3"); | |
strcpy(src, "abcde"); // src is longer | |
memset(dest, 'w', sizeof(dest)); | |
strncpy(dest, src, 1); | |
dump_dest("long1"); | |
memset(dest, 'w', sizeof(dest)); | |
strncpy(dest, src, 2); | |
dump_dest("long2"); | |
memset(dest, 'w', sizeof(dest)); | |
strncpy(dest, src, 3); | |
dump_dest("long3"); | |
memset(dest, 'w', sizeof(dest)); | |
strncpy(dest, src, 4); | |
dump_dest("long4"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment