-1
#include <stdio.h>
void func1(char *a);
int main()
{
        char *mStat="welcome home";
        printf("Text before: (%s)\n",mStat);
        func1(mStat);
        printf("Text after: (%s)\n",mStat);
        return 0;
}


void func1(char *a)
{
        printf("Input: (%s)\n",a);
        a[1]='a';
}

This program crashes with a segfault all the time in the line where I am modifying the character in the string. What is wrong with it ? What is the correct way of doing it ?

user1872325
  • 71
  • 1
  • 9
  • 5
    You are modifying a "string literal". Change `char *mStat="welcome home";` to `char mStat[]="welcome home";` – haccks Mar 31 '16 at 05:31
  • That was really helpful. Been a while since I did C. More information on the same problem is found here: http://stackoverflow.com/questions/12795850/string-literals-pointer-vs-char-array – user1872325 Mar 31 '16 at 05:35

2 Answers2

1

You are modifying a string literal. Such an operation is compiler dependent. As stated here (http://en.cppreference.com/w/cpp/language/string_literal):

Attempting to modify a string literal results in undefined behavior: they may be stored in read-only storage (such as .rodata) or combined with other string literals.

It seems that in your case you actually trying to modify read-only storage

GMichael
  • 2,726
  • 1
  • 20
  • 30
1

char *mStatis a const string literal in C.You can not modify the assigned value.

If you want to modify it, you should use this: char mStat[]="welcome home";

GorvGoyl
  • 42,508
  • 29
  • 229
  • 225