fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. int main()
  5. {
  6. char a[3], b[4];
  7.  
  8. // a will have a lower address in memory than b
  9. printf("%p %p\n", a, b);
  10.  
  11. // "abc" is a null terminated literal use a size of 4 to force a copy of null
  12. strncpy(a,"abc",4);
  13. // printf will not overrun buffer since we terminated it
  14. printf("a2 = %s\n", a);
  15.  
  16. // explicitly only copy 3 bytes
  17. strncpy(b,a,3);
  18. // manually null terminate b
  19. b[3] = '\0' ;
  20.  
  21. // So we can prove we are seeing b's contents
  22. b[0] = 'z' ;
  23.  
  24. // This will overrun into b now since b[0] is no longer null
  25. printf("a2 = %s\n", a);
  26. printf("b = %s\n", b);
  27.  
  28. }
Runtime error #stdin #stdout 0s 1788KB
stdin
Standard input is empty
stdout
0xbfe3d4e9 0xbfe3d4ec
a2 = abc
a2 = abczbc
b = zbc