segmentation fault in C by replacing a string's letter [duplicate]

天涯浪子 提交于 2020-01-05 05:24:25

问题


I want to replace a character (for example the second one) from a string. What's wrong with my code? It can compile, but instead of doing what I need it give me a Segmentation fault. Thanks!

#define _XOPEN_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <cs50.h>
#include <string.h>

int main (int argc, string argv[])
{
    string key="abcd";
    key[1]='f';
}

And after compiled my code

~/workspace/pset2/crack/ $ clang -ggdb3 -O0 -std=c11 -Wall -Werror -Wshadow bug.c -lcrypt -lcs50 -lm -o bug
~/workspace/pset2/crack/ $ ./bug
Segmentation fault

回答1:


You can only modify memory that is in the heap or stack, your "abcd" there is what is known as a String Literal and belongs in the program's read-only memory space, it cannot be modified where it is (not if it's running under any decent operational system anyway).

The reason it's placed there to begin with is because string is basically just a char * pointer, and it will point to any memory space and doesn't care if it's in read-only space or not. (not to be confused with C++ std::string).

To make it modifiable you have to tell C it's not a pointer, but an array.

char key[] = "abcd";

Now C will place this string in the stack where you can modify it at will.




回答2:


string key="abcd";

string is basically char * ,key is string literal. You try to modify it, therefore the segmentation fault.




回答3:


I do not see the definition of name string but I think it is something like char *.

Thus in this declaration

 string key="abcd";

there is declared a pointer to a string literal.

String literals are unmodified in C, Any attempt to modify a string literal results in undefined behavior.

From the C Standard (6.4.5 String literals)

7 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.




回答4:


This is because "abcd" is not really copied into your key variable. Instead, key is a pointer to this constant string.

If you want to be able to modify it, you can do this :

int main (int argc, string argv[])
{
    char key[] = { "some string" };
    key[1]='f';
}


来源:https://stackoverflow.com/questions/40960596/segmentation-fault-in-c-by-replacing-a-strings-letter

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