程序崩溃时释放字符数组 [英] Programme crashes while deallocating a character array

查看:100
本文介绍了程序崩溃时释放字符数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行的.exe是用调试模式下面的代码创建的,它显示一些断言失败和程序崩溃但是当我运行相同的exe创建从下面的代码的发布模式,其工作正常。 / p>

请帮助确定为什么我在调试模式下取消断言失败,而不是在释放模式下。

 #include< iostream> 
using namespace std;
#include< string.h>

void main()
{
char * buf = new char [5]; //预分配缓冲区
buf =Hello;
delete [] buf;
getchar();
// cout<< buf;
// string * p = new(buf)string(hi); // placement new
// string * q = new string(hi); //普通堆分配
}


解决方案

p> char * buf = new char [5]; //预分配缓冲区

这里你定义一个指针,并初始化它指向一个动态分配

  buf =Hello; 

这里你初始化指针指向字符串文字的开头。

  delete [] buf; 

这里你删除[] buf指针,但是buf指针不再指向任何你新的[ ]'d,它指向字符串字面量。你只能删除/删除[]一个指针,指向你从新的/新的[]。所以你得到未定义的行为,可能会崩溃



你可能想把你的字符串的内容复制到你的新缓冲区[]'d。请记住nul终结符的帐户:

  int main()
{
char * buf = new char [6]; // pre-allocated buffer
strcpy(buf,Hello);
delete [] buf;
getchar();
// cout<< buf;
// string * p = new(buf)string(hi); // placement new
// string * q = new string(hi); //普通堆分配
}

然而,在C ++中, :: string from #include< string> ;

  std: :string =Hello; 


When I run the .exe being created with the below code in debug mode , it shows some assertion failure and the programme crashes But when i run the same exe created from the release mode of the below code , its working fine.

Please help to identify why I am geting the assertion failure in debug mode but not in release mode .

#include<iostream>
using namespace std;
#include<string.h>

void main()
{
    char *buf  = new char[5];   //pre-allocated buffer
    buf = "Hello";
    delete [] buf;
    getchar();
    //cout<<buf;
    //string *p = new (buf) string("hi");  //placement new
    //string *q = new string("hi");  //ordinary heap allocation
}

解决方案

 char *buf  = new char[5];   //pre-allocated buffer

Here you define a pointer, and initialize it to point to a dynamically allocated buffer with room for 5 characters.

buf = "Hello";

Here you initialize the pointer to point to the beginning of a string literal.

 delete [] buf;

Here you delete[] the buf pointer, but the buf pointer no longer points to anything you new[]'d up, it points to the string literal. You can only delete/delete[] a pointer that points to something you got from new/new[]. So you get undefined behavior, and likely crash

You likely meant to copy the content of your string into the buffer you new[]'d. Remember to account for the nul terminator:

int main()
{
    char *buf  = new char[6];   //pre-allocated buffer
    strcpy(buf, "Hello");
    delete [] buf;
    getchar();
    //cout<<buf;
    //string *p = new (buf) string("hi");  //placement new
    //string *q = new string("hi");  //ordinary heap allocation
}

Though, in C++, you'd rather use std::string from #include <string>;

std::string = "Hello";

这篇关于程序崩溃时释放字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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