Find the answer to your Linux question:
Results 1 to 3 of 3
If I do something similar to this : Code: char *g_text = "abcde"; void main(void) { g_text[2] = 'x'; } I get a segmentation fault. I'm guessing its not allowed ...
  1. #1
    Just Joined!
    Join Date
    Sep 2008
    Posts
    1

    Is this allowed ?

    If I do something similar to this :
    Code:
    char *g_text = "abcde";
    
    void main(void)
    {
      g_text[2] = 'x';
    }
    I get a segmentation fault. I'm guessing its not allowed to change memory assigned like this, but is there a way to do this ? maybe a compiler setting or something ?

    I know I could write this totally different and use malloc etc, but I'm porting existing code from sco unix to redhat linux and there are a lot of variables like these, so making it work would mean a lot of extra work.

  2. #2
    Linux Engineer GNU-Fan's Avatar
    Join Date
    Mar 2008
    Posts
    935
    Hello,

    the ANSI C standard says that these so called "string literals" are to be assumed unmodifiable and any try to modify them at runtime will result in undefined behaviour. 3.1 Lexical Elements


    Therefore, it's better to write.

    Code:
    const char *g_text = "abcde";
    If you want to be able to modify it later, you could reserve a constant sized array and have it initialized automatically with such a string.
    Code:
    char g_text[] = "abcde";
    The size of the array will be set by compiler automatically so that the string and the trailing 0 fits in. But the size will stay constant.
    Debian GNU/Linux -- You know you want it.

  3. #3
    Linux Enthusiast gerard4143's Avatar
    Join Date
    Dec 2007
    Location
    Canada, Prince Edward Island
    Posts
    714
    if your create a variable like:

    char *g_text = "abcde";

    it will produce a variable in the section called rodata(read only data) which is read only.

    while char g_text[] = "abcde"; does not

    try compiling your program with gcc -S programname.c and look at the programname.s file, in the first example you'll see the rodata section in the second you won't


    so is this allowed...g_text[2] = 'x'....no its not...hope this helps...Gerard4143

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...