0

Why does the code fail with a segmentation fault for the first set of code but the second block doesn't? (Only difference is that the chars are static in the first but not static in the second).

#include <string.h> 
#include <stdio.h>
static char a[16];
static char b[16];
static char c[32];
int main(int argc, char *argv[]) {
    strcpy(a, "0123456789abcdef");
    strcpy(b, "0123456789abcdef");
    strcpy(c, a);
    strcat(c, b); 
    printf("a = %s\n", a);
    return 0;
}

.

#include <string.h> 
#include <stdio.h>
char a[16];
char b[16];
char c[32];
int main(int argc, char *argv[]) {
    strcpy(a, "0123456789abcdef");
    strcpy(b, "0123456789abcdef");
    strcpy(c, a);
    strcat(c, b); 
    printf("a = %s\n", a);
    return 0;
}

At first I thought it's because of where they are stored but they are both in the bss region (both global and uninitialized). From what I understood and read here on Stackoverflow, all static does is make the variable limited to an internal linkage but nothing else.

(I know that there is no space allocated for the null character. This behavior is consistent).

  • Related to [Is accessing a global array outside its bound undefined behavior?](http://stackoverflow.com/q/26426910/1708801) – Shafik Yaghmour Apr 08 '15 at 04:04
  • 6
    Undefined behaviour is undefined; you'll have to look at the specific assembly/binary output for your programs on your system and toolchain to see why there might be a difference. FWIW, I just tried both of your programs here, and they all abort trap on my machine, regardless of optimization level. – Carl Norum Apr 08 '15 at 04:05

2 Answers2

3

Just because of luck. Whenever, you cross the boundary of the defined limit of an array (be it static or just global, whatever), there is no array boundary check in C, as such, you may or may not get runtime violations, where the luck factor comes in. You need to allocate extra space including the string null terminator:

char a[16+1];
char b[16+1];
char c[32+1];
Dr. Debasish Jana
  • 6,980
  • 4
  • 30
  • 69
2

Basically what you have in both the code snippet is Array out of bound access and this will lead to undefined behavior. So there are chances that the first code snippet might crash on some other system. Since the behavior is not defined anything might happen and in your case you are lucky and don't see a crash(1st code snippet) but you can never rely on this.

Gopi
  • 19,784
  • 4
  • 24
  • 36