Skip to content

Instantly share code, notes, and snippets.

@sineemore
Created October 31, 2018 00:02
Show Gist options
  • Save sineemore/cb40f16b35df7fb73553229ced9f1722 to your computer and use it in GitHub Desktop.
Save sineemore/cb40f16b35df7fb73553229ced9f1722 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void) {
int count = 9;
char *buf = calloc(count + 1, 1);
fread(buf, count, 1, stdin);
char a[7]; // 6 chars + \0
strncpy(a, buf, sizeof(a) - 1);
a[sizeof(a) - 1] = '\0'; // strncpy doesn't add \0
printf("a: '%s'\n", a);
char b[7] = {0}; // explicit zeroing
strncat(b, buf, sizeof(b) - 1);
printf("b: '%s'\n", b);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment