Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programme crashes while deallocating a character array

Tags:

c++

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
}
like image 706
Viku Avatar asked Jan 30 '26 16:01

Viku


2 Answers

 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";
like image 151
nos Avatar answered Feb 02 '26 07:02

nos


  1. void main is wrong. main returns int. No exceptions.
  2. You're doing delete[] "Hello". "Hello" is a string literal; you can't delete it.
like image 22
melpomene Avatar answered Feb 02 '26 07:02

melpomene