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!
You allocated 80 bytes in b, so will delete[]free 80 bytes. What you did with the array doesn't matter, though.
b
delete[]
(Unless, of course, you messed up the heap, in which case delete[]it probably will crash.)
EDIT: , b - , delete[] b; delete b;. , , .
delete[] b;
delete b;
- . , , , , . , , .
1) be delete [] b; undefined 2) std::string std::vector, .
delete [] b;
std::string
std::vector
, , . .
right delete. , [], [].
:
If you select one element, use delete; if you select an array, use delete [].
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.
new/delete
#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; }
The code you sent is broken. Please review this topic: What is the shape of the 'delete' array?
GL
Source: https://habr.com/ru/post/1772692/More articles:JUnit Test Proposal - unit-testingUsing fancybox on a loaded AJAX page - jqueryКак объявить класс динамически? С# - reflectionEclipse IDE проблема "не win32-приложение" - eclipseJava Creates a new Map.Entry array - javaCreating a DOM document using tagoup - javaOpenCl development on ATI and Nvidia at the same time - openclGWT Layout: "take the rest of the space." - layoutConcurrentHashMap examples - javaDelphi, what is the fastest way to write to TcxGrid or TDataSet - delphiAll Articles