开发者

Why does this code snippet give segmentation fault

This piece of code throws seg fault.Please help me identify the reason for the same

#include<stdio.h>
开发者_开发知识库
int main() {
        char* str;
        str = "abcd";
        str[0] = 'r';
        printf("%c\n" , str[0]);
        return 0;
}

thanks


Well explained in C FAQ 1.32. It's illegal to modify string literals.

6.4.5/6

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.


    str = "abcd";
    str[0] = 'r';

This attempts to modify a string literal. Officially, that's undefined behavior. On most modern systems, however, the memory holding string literals will be marked read-only, so attempting to modify them will give a fault.


This is similar Question related to Segmentation Fault

Refer this for more info.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜