C ++ NULL字符和内存分配

时间:2017-07-30 13:26:09

标签: c++ string

我有一个如下的迷你C ++程序,

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

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

我只想确认在“Hello”字符串之后不会输出'W',因为NULL字符。但是,此程序显示运行时错误如下:

  

抛出未处理的异常:写入访问冲突。    userInput 是0xBD9BD8。发生

有任何建议或意见吗?非常感谢。

3 个答案:

答案 0 :(得分:1)

执行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";
}

答案 1 :(得分:0)

当你写下:

userInput = "Hello";

指针userInput将指向&#34; Hello&#34; string,长度为6个字节,5个字符+空终止符。 (顺便说一句,你的new char[7]无用)

在这里:

*(userInput + 6) = 'W';

您在空终结符之后写入内存中尚未分配的内容。 在未分配的内存中读/写时发生的是未定义的行为,例如它可能导致seg故障,你有

答案 2 :(得分:0)

该程序存在一些问题。

首先是内存泄漏。

char* userInput = new char[7];
userInput = "Hello";

首先,指针userInput由分配的内存范围的地址初始化,然后使用字符串文字"Hello"的第一个字符的地址重新分配指针。

虽然程序试图在字符串文字之外的内存中写入但是应该提到根据C ++标准(2.13.5字符串文字)

  

16评估字符串文字会产生字符串文字对象   静态存储持续时间,从给定字符初始化为   如上所述。是否所有字符串文字都是不同的(即,   存储在非重叠对象中)以及是否连续   对字符串文字的评估产生相同或不同的对象   没有具体说明。 [注意:尝试修改字符串的效果   字面值未定义。 - 后注]

为了演示您的概念,不需要动态分配内存。你可以写

char userInput[7] = "Hello";
*(userInput + 6) = 'W';

或者使用动态内存分配,您可以编写

#include <cstring>

//...

char* userInput = new char[7];

std::strcpy( userInput, "Hello" );
*(userInput + 6) = 'W';
//...
delete [] userInput;

注意尽管有些编译器(据我所知MS VC ++允许这样做)允许声明函数main为具有返回类型void但是根据C ++标准,函数main应具有返回类型中间体

int main()
相关问题