1

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

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for clearing this with detailed explanation and C FAQ is definitely a treasure
3
    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.

Comments

0

This is similar Question related to Segmentation Fault

Refer this for more info.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.