简体   繁体   中英

segmentfault when modify char * const pstr = “abcd”;

char * const pstr = "abcd"; pstr is a const pointer to char... I think that I can't modify the pstr, but I can modify *pstr, So I write the next code

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
    //  The pointer itself is a constant,
    //  Point to cannot be modified,
    //  But point to a string can be modified
    char * const pstr = "abcd";  //  Pointer to a constant

    // I find that pstr(the address of "abcd") is in ReadOnly data
    // &pstr(the address of pstr) is in stack segment
    printf("%p  %p\n", pstr, &pstr);

    *(pstr + 2) = 'e';  //  segmentation fault (core dumped)
    printf("%c\n", *(pstr + 2));

    return EXIT_SUCCESS;
}

But the result is not as I expected. I got a segmentation fault (core dumped) at the line 14... So I write the next code

#include <stdio.h>
#include <stdlib.h>


int main(void)
{
    //  The pointer itself is a constant,
    //  Point to cannot be modified,
    //  But point to a string can be modified
    char * const pstr = "abcd";  //  Pointer to a constant

   // I find that pstr(the address of "abcd") is in ReadOnly data
   // &pstr(the address of pstr) is in Stack segment
   printf("%p  %p\n", pstr, &pstr);

   *(pstr + 2) = 'e';  //  segmentation fault (core dumped)
   printf("%c\n", *(pstr + 2));

   return EXIT_SUCCESS;

}

But I don't know why???

char * const pstr = "abcd"; 

pstr is a constant pointer to char and you can't modify pstr correct , but "abcd" is a string iteral . And you can't modify string literal .

You try to modify it and therefore , you get a segmentation fault .

In C language , If i will write

char *ptr = "abcd"

you can not change *(ptr+2) = 'e' , even if you don't write const. as in C language if you declare like char *ptr = "abcd" , it will treat ptr as constant character string.

so it will give segmentation fault in this code also ..

char *ptr = "abcd";
*(ptr+2) = 'e';

but , you can do this ::

char ptr[] = "abcd";
*(ptr+2) = 'e';

char * const pstr = "abcd"

This is pointer initialization. so "abcd" is stored in code section of Memory. you can not modified code section of Memory. it is read only memory. so. OS will generate segmentation fault during run time because of accessing unauthorised memory.

char pstr[]="abcd";

now, "abcd" stored in data section so u can modified.

由数组初始化的黑白字符串与由指针初始化的字符串的区别是指针字符串无法修改。原因是指针字符串存储在代码存储器中,而数组字符串存储在堆栈(如果是全局数组,则存储在堆中)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM