通过替换字符串的字母在C中进行分段错误 [英] segmentation fault in C by replacing a string's letter
问题描述
我想从字符串中替换字符(例如第二个字符)。
我的代码有什么问题?它可以编译,但是没有执行我需要的操作,而是给我一个Segmentation Fault。谢谢!
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';
}
在编译我的代码后
~/workspace/pset2/crack/ $ clang -ggdb3 -O0 -std=c11 -Wall -Werror -Wshadow bug.c -lcrypt -lcs50 -lm -o bug
~/workspace/pset2/crack/ $ ./bug
Segmentation fault
推荐答案
您只能修改堆或堆栈中的内存,您的 abcd
称为字符串文字,属于程序的只读内存空间,因此不能在其中进行修改(无论如何,它都不能在任何合适的操作系统下运行)。
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).
放置在程序中的原因首先是因为 string
基本上只是一个 char *
指针,它会指向任何内存空间,并且不会不在乎它是否位于只读空间中。 (不要与C ++ std :: string
混淆)。
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
).
要使其可修改,您必须告诉C
To make it modifiable you have to tell C it's not a pointer, but an array.
char key[] = "abcd";
现在C将把此字符串放在堆栈中,您可以随意对其进行修改。
Now C will place this string in the stack where you can modify it at will.
这篇关于通过替换字符串的字母在C中进行分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!