为什么这个简单的字符串分配段错误? [英] Why does this simple string assignment segfault?

查看:250
本文介绍了为什么这个简单的字符串分配段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

#include <iostream>
using namespace std;
int main()
{
    char* a = "foo";
    char* b = "bar";
    a = b;
    cout << a << ", " << b << endl;
    return 0;
}

这可以编译工作,即.打印bar, bar.现在,我想证明这里发生的事情不是复制字符串.我想更改b并显示a也会更改.我想出了这个简单的代码:

This compiles and works, ie. prints bar, bar. Now I would like to demonstrate that what goes on here is not copying a string. I would like to change b and show that a also changes. I came up with this simple code:

#include <iostream>
using namespace std;
int main()
{
    char* a = "foo";
    char* b = "bar";
    a = b;
    b[1] = 'u'; // ← just this line added
    cout << a << ", " << b << endl;
    return 0;
}

...但是它存在段错误.为什么?有趣的是,以下修改可以正常运行:

…but it segfaults. Why? The interesting thing is that the following modification runs just fine:

#include <iostream>
using namespace std;
int main()
{
    char* a = "foo";
    char b[] = "bar"; // ← declaration changed here
    a = b;
    b[1] = 'u';
    cout << a << ", " << b << endl;
    return 0;
}

为什么它不像前一个那样出现段错误?我想我缺少了指针样式和数组样式的字符串初始化之间的一些重要区别.

Why doesn’t it segfault like the previous one? I guess I am missing some important difference between the pointer-style and the array-style string initialization.

推荐答案

您不能更改字符串常量,这是使用第一个代码示例中的使用字面量语法时得到的.

You cannot change string constants, which is what you get when you use the pointer-to-literal syntax as in the first code samples.

另请参阅以下问题:是字符串文字在静态内存中创建的C ++中?.

这篇关于为什么这个简单的字符串分配段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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