Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ new/delete and char *

Tags:

Can anyone help me, why I'm getting an error message while trying to free the allocated memory: Heap corruption detected. CTR detected the application wrote the memory after end of heap buffer.

char *ff (char *s){     char *s1 = new char [strlen(s)];     strcpy(s1, s);     return s1; }  int _tmain(int argc, _TCHAR* argv[]) {     char *s = new char [5];      strcpy(s, "hello");     char *s2 = ff(s);      delete []s;     // This works normal     delete []s2;    // But I get an error on that line     return 0; } 
like image 332
a3dsfcv Avatar asked Nov 06 '12 08:11

a3dsfcv


People also ask

What char * means in C?

char* means a pointer to a character. In C strings are an array of characters terminated by the null character.

How do I delete a char pointer?

List of points to be noted: 1) You need to allocate room for n characters, where n is the number of characters in the string, plus the room for the trailing null byte. 2) You then changed the thread to point to a different string. So you have to use delete[] function for the variable you are created using new[] .

What is new char in C++?

You can create an array with zero bounds with the new operator. For example: char * c = new char[0]; In this case, a pointer to a unique object is returned. An object created with operator new() or operator new[]() exists until the operator delete() or operator delete[]() is called to deallocate the object's memory.

How do I create a new character in C++?

To declare a char variable in C++, we use the char keyword. This should be followed by the name of the variable. The variable can be initialized at the time of the declaration. The value of the variable should be enclosed within single quotes.


1 Answers

char *s = new char [5]; strcpy(s, "hello"); 

Causes Undefined behavior(UB).
You are writing beyond the bounds of allocated memery. You allocated enough memory for 5 characters but your string has 6 characters including the \0.

Once your program has caused this UB, all bets are off and any behavior is possible.

You need:

char *s = new char [strlen("hello") + 1]; 

In fact the ideal solution is to use std::string and not char *. These are precisley the mistakes which std::string avoids. And there is no real need of using char * instead of std::string in your example.
With std::string:

  • You don't need to new anything
  • You don't need to delete anything &
  • You can do everything with std::string, that you do with char *.
like image 62
Alok Save Avatar answered Sep 19 '22 16:09

Alok Save