Question

I'm a complete noob at C and i need some help understanding why a certain piece of code compiles correctly.

main(){
    char name[3];
    strcpy(name, "12345678912312");
    printf("%s\n",name);
}

So this code compiles correctly;however, I don't understand why it does not cause a segmentation fault. From my understanding of c, each character is 1 byte. The array name, is supposed to be able to hold 3 bytes, instead it can hold a lot more than that. Why is that?

Additionally, if I add one more character to this, I will get Illegal Instruction(core dumped).

main(){
    char name[3];
    strcpy(name, "123456789123121");
    printf("%s\n",name);
}

Then if I add another character to that code, it will throw a Segmentation fault (core dumped) error. Why are the errors different? And why did they not occur before?

And lastly, where can I find documentation for each function? I’m coming from java so I am used to referencing to the java docs.

Im using GCC compiler in Ubuntu linux.

Was it helpful?

Solution

Both of code invokes undefined behavior because you are writing to an un-allocated memory location. In this case anything could happen. Either your program runs and may or may not give the expected output or it will crash or give segmentation fault.
Also note that strcpy doesn't check for array bound and compiler doesn't raise any warning/error for it.

OTHER TIPS

If you read a few questions here on SO you will hear a lot about "undefined behaviour", often abbreviated to UB.

What it means is that if your program does something outside the C standards, the standards do not define what will happen. Anything can happen.

Writing past the end of an array is one example of something that can trigger UB.

C does not do array bound checking, so if you try to write beyond the end of the array, the results will depend on how the compiler implements arrays, how they are arranged in memory, and what lies after them. The point, however, is that you cannot rely on any particular behaviour.

My favourite reference site for C and C++ is cppreference. But on Linux you can also read the definition of library functions with man, eg. man strcpy.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top