Home > Back-end >  Why is it not giving segmentation fault?
Why is it not giving segmentation fault?

Time:07-04

I have a question about using pointer.

char *CustomString;
char str[5] = {'V', 'i', 'c', 't', '\0'};
CustomString = (char*) malloc(1);
strcpy(CustomString, str);
printf("%s\n", CustomString);

Why is it not giving "segmentation fault"?

The result is an output:

Vict

CodePudding user response:

When you write past the bounds of allocated memory, you trigger undefined behavior. That means the compiler makes no guarantees regarding what the program will do. It may crash, it may output strange results, or it may appear to work properly.

Just because the program could crash doesn't mean it will.

CodePudding user response:

To answer your question most directly, when allocating memory most compilers' memory management schemes will adjust the allocation boundary to some fixed amount, often 16 bytes or 64 bytes. So when you allocated one byte, you actually likely got more than 1 byte. But this is behind-the-scenes behavior, and it is a VERY BAD IDEA to write any code that depends on this behavior. Change compilers (or even upgrade to a newer version of the same compiler) and all hell could break loose. It's called undefined behavior for a reason.

  • Related