通过替换字符串的字母在 C 中出现分段错误 [英] segmentation fault in C by replacing a string's letter

查看:17
本文介绍了通过替换字符串的字母在 C 中出现分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想替换字符串中的一个字符(例如第二个).我的代码有什么问题?它可以编译,但它没有做我需要的事情,而是给了我一个分段错误.谢谢!

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" 有所谓的 String Literal并且属于程序的只读内存空间,不能修改它所在的位置(无论如何,如果它在任何体面的操作系统下运行,则不能修改).

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆