gpt4 book ai didi

C++ NULL 字符和内存分配

转载 作者:行者123 更新时间:2023-11-30 05:10:55 25 4
gpt4 key购买 nike

我有一个迷你 C++ 程序,如下所示。

#include <iostream>
using namespace std;
void main() {

char* userInput = new char[7];
userInput = "Hello";
*(userInput + 6) = 'W';
cout << userInput << "\n";
}

我希望在整个这样的程序中,确认不会输出“W”,因为 NULL 字符紧跟在“Hello”之后。但是,它显示以下运行时错误。

Unhandled exception thrown: write access violation.userInput was 0xBD9BD8. occurred

有什么建议吗?谢谢。

最佳答案

当您执行 userInput = "Hello"; 时,您实际上将变量 userInput 重新分配给字符串 "Hello"

但字符串 "Hello" 并未复制到您的缓冲区 new char[7] 中,变量 userInput重新分配.

因此您的缓冲区保持不变。

因为字符串文字(在代码中用引号" 编写的字符串)存储在程序的只读部分,您不能重写它们的任何字符:这就是为什么你有错误。

在这里,最糟糕的是:您正试图在只读存储器中写入越界的字符串。这不是错误的原因(如其他人所述),因为那里还有其他填充数据,原因是该区域被写保护。

使用 strcpy() 等函数将字符串复制到另一个缓冲区。

#include <iostream>
#include <string.h>

using namespace std;

int main() {
char* userInput = new char[7];

strcpy(userInput, "Hello");
*(userInput + 6) = 'W';
cout << userInput << "\n";
}

关于C++ NULL 字符和内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45400291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com