简体   繁体   中英

How to clear dynamic array in C++ and how much is on the stack?

I have a struct in my C++ program. At the end of my function I do a delete [] to free the allocated memory. How do I erase all elements in code without doing a for() loop?

struct sServerStatus
{
    TCHAR sServer[MAX_COMPUTERNAME_LENGTH+1]; // The NetBIOS name of the computer + 1 null terminating character.
};
sServerStatus *sServersType1 = new sServerStatus[1024];

Q1. How do I clear the array after I fill some of the items up? Do I use SecureZeroMemory?

SecureZeroMemory(sServersType1 , sizeof(sServersType1 ));

Q2. What is on the stack? I assume the allocated space on the stack is just MAX_COMPUTERNAME_LENGTH+1 and the 1024 elements are on the heap?

  1. new sServerStatus[1024]; will allocate 1024 sServerStatus instances on the heap .

  2. Each one of those has MAX_COMPUTERNAME_LENGTH+1 TCHAR s. (Also on the heap since that's where the objects are allocated.)

The only thing on the stack is the pointer sServersType1 .

To clean everything up, note that you didn't use new to allocate (2) so you don't need to use delete either. That memory will be freed once an sServerStatus instance is destructed.

But you will need to free the memory you allocated using new . Do do this you need to write delete[] sServersType1 . Note carefully the [] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM