Possible Duplicate:
Why don’t I get a segmentation fault when I write beyond the end of an array?
I was just playing with pointers when I realized that something strange was happening. I am aware that whenever we want to copy a string src to another string dst, using strcpy, for instance, we should allocate the required space for src.
char *dst,*src = "asdlskafksdhfklshfkshdkfhksdhfçsahdflçsdhfçklshadfç";
dst = (char*)malloc(1); //only one char allocated
strcpy(dst,src);
printf("dst=%s.\n",dst);
This code should not execute. However that is not happening. The code executes, copies successfully the src into dst and prints dst like a charm. Could someone of you, explain me why is this happening, please?
Part of the performance of C is that it does not have much in the way of built in error checking. All
strcpyknows is that it was passed a pointer of the correct type, it doesn’t know how much allocated memory it was pointing at. The resulting machine code simply reads from the src pointer up to the first null byte and then pastes it into the dst pointer. If it doesn’t overwrite somebody else’s memory, there is no error.What is “someone else’s memory”? Generally a process is allocated memory in pages. When you malloc one byte, the process is given a whole page of memory, probably a few kilobytes, to slice and dice as it needs. Segmentation faults occur when your process tries to write outside its allocated pages, and for other reasons. The error is typically generated by the operating system and/or hardware which is doing the memory management. Since src is only a few dozen bytes it is unlikely to walk outside the process’ page. If you make src a longer string, you’ll probably get the segfault you’re expecting.
There are various malloc wrapper libraries used for debugging which, through various tricks, make C check for memory mistakes. Valgrind and Electric Fence being some of the most famous.
PS I’m a little hazy on exactly how this stuff works, but its more satisfying than “it’s undefined behavior”. Please feel free to edit where my explanation is lacking.