Bad permissions for mapped region [duplicate]

妖精的绣舞 提交于 2019-12-30 10:44:13

问题


I get an error when trying to run the following function:

   char* reverseInPlace(char* src)
{
    //no need to alloc or free memory
    int i=0;
    int size=mystrlen(src);
    for(i=0;i<size;i++)
    {
        int j=size-i-1;

        if(i<j)
        {
            char temp;
            printf("Interchange start %d:%c with %d:%c",i,src[i],j,src[j]);
            temp=src[i];
            src[i]=src[j];//error occurs here
            src[j]=temp;
            printf("Interchange complete %d:%c and %d:%c",i,src[i],j,src[j]);
        }   
    }
    return src; 
}

I call this code like this:

char* rev2=reverseInPlace("BeforeSunrise");
printf("The reversed string is %s\n",rev2);

The error looks like this:

Interchange start 0:B with 12:e
Process terminating with default action of signal 11 (SIGSEGV)
Bad permissions for mapped region at address 0x401165

Why does this error occur?


回答1:


You are passing a constant string to your function.

String literals are of type char [N + 1] (where N is the length of the array) in C, but modifying them results in undefined behavior. Your compiler should have already issued a warning at that point.

If you wish to modify it then you have to create a copy:

char str[] = "BeforeSunrise";
char* rev2=reverseInPlace(str);



回答2:


It's because you try to modify a string literal, which is a constant array, i.e. it's read-only.



来源:https://stackoverflow.com/questions/21387972/bad-permissions-for-mapped-region

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!