JeffR
JeffR

Reputation: 805

How do I clear an array of a structure in C, and then free that memory?

Two questions:

  1. How to quickly clear an array of a structure?
  2. How to free memory allocated by the structure's member?

Code:

struct sComputerNames
{
    TCHAR *sName;   // Using a pointer here to minimize stack memory.   
};

TCHAR *sComputer  = (TCHAR *) calloc(2048+1, sizeof(TCHAR));
struct sComputerNames sCN[4096] = {0};


_tcscpy(sComputer,L"PC1");
sCN[0].sName = (TCHAR *) calloc(128,sizeof(TCHAR));
_tcscpy_s(sCN[0].sName,128,sComputer);


// What is a better way to clear out the structure array?
for (DWORD i=0;i<4096;i++)
{
    free(sCN[i].sName);
    sCN[i].sName=NULL;
}


// Assign a new value
_tcscpy(sComputer,L"PC2");
sCN[0].sName = (TCHAR *) calloc(128,sizeof(TCHAR));
_tcscpy_s(sCN[0].sName,128,sComputer);


free(sCN);sCN=NULL;     // Erroring here - how to free memory allocated by sCN's members?
free(sComputer);sComputer=NULL;

Thank you!

Upvotes: 1

Views: 14213

Answers (3)

octopusgrabbus
octopusgrabbus

Reputation: 10695

You are trying to free from the structure head, but it's not a pointer, and if it were, you would still want to free the sName pointer's memory first.

You would free sCN[idx].sName -- where idx would be assigned by a for loop. If you want to zero the structure -- was not clear from your question -- call memset using sCN[idx] as the starting address, 0 as the set value, and sizeof(sCN[idx]) as the length of the structure.

You would also have to free the memory of sComputer.

Upvotes: 0

blueshift
blueshift

Reputation: 6891

Clearing the array is easy:

memset(sCN, 0, sizeof(sCN));

As for the rest, you have some confusion about trying to free sCN which you didn't malloc(), and trying to free lots of names when you only calloc()'d one of them.

Upvotes: 5

jpinto3912
jpinto3912

Reputation: 1465

While some libs have heap_min, or by other names, that will reset the allocation pools used by m/calloc and free, you're doing it very right.

Bear in mind that allocation pools are most commonly implemented using linked lists of allocation information nodes. On your example there will be a truck load of sequential callocs, hence the order by which you free should be the same order by which you allocated. That means the free call will find the element to free in the beginning of the linked list, minimizing search time.

Upvotes: 0

Related Questions