Does strcpy'ing eliminate a string in a larger char array memory leak?

Hi everyone, just wondering if the following could cause a memory leak?

char* a = "abcd"
char* b = new char[80];

strcpy(b, a);

delete[] b;

Will the entire block of 80, or only 4 characters, be copied into it using strcpy? Thank!

+3
source share
5 answers

You allocated 80 bytes in b, so will delete[]free 80 bytes. What you did with the array doesn't matter, though.

(Unless, of course, you messed up the heap, in which case delete[]it probably will crash.)

EDIT: , b - , delete[] b; delete b;. , , .

+11

- . , , , , . , , .

1) be delete [] b; undefined 2) std::string std::vector, .

+5

, , . .

right delete. , [], [].

:

delete[] b;

If you select one element, use delete; if you select an array, use delete [].

+4
source

Since it is marked with C ++, here the C ++ version is to understand memory management well through new/delete, but it is better not to do it manually using RAII.

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

int main()
{
    string a("abcd");
    string aCopy(a);
    cout << aCopy << endl;

    const char* b(aCopy.c_str());
    cout << b << endl;
}
+1
source

The code you sent is broken. Please review this topic: What is the shape of the 'delete' array?

GL

0
source

Source: https://habr.com/ru/post/1772692/


All Articles