JeffR
JeffR

Reputation: 805

Is my C structure and memory allocation correct?

Not sure if I have the correct syntax; my code is working, just want to run it past anyone that would like to comment to help improve it. I assume that allocating 20480 is not consuming any space because it's just an array of pointers? So I can make it go to any number that is larger than dwStringsFound?

    struct sArray   {
    TCHAR *sName;
    }*sKeys[20480];

    // get dwStringsFound...
    [...]

    // allocate the space
    for (DWORD i=0;i<dwStringsFound;i++) sKeys[i] = (sArray *) calloc(1,sizeof(sArray));
    for (DWORD i=0;i<dwStringsFound;i++) sKeys[i]->sName = tcalloc(1024);

    // Do work...
    [...]

    // Free resources.
    for (DWORD i=0;i<dwStringsFound;i++)    {
    free(sKeys[i]->sName);sKeys[i]->sName=NULL;
    free(sKeys[i]);sKeys[i]=NULL;
    }

Upvotes: 0

Views: 119

Answers (2)

Michael Wu
Michael Wu

Reputation: 1277

Static allocation is fine, but it isn't the most memory efficient. In the future you may want to consider allocating **sKeys to be an array of sArray with dwStringsFound being the size of this array. Where you will run into trouble with your current method is if you call a deeply recursive function at some point in your program, you may run out of stack memory. Remember, there is always more heap memory than stack memory. If you don't plan on using something for the entirety of a program, it should probably be malloc'ed and freed. If it's just statically assigned, it is just wasting space after it outlives it's usefulness.

Upvotes: 0

user2123629
user2123629

Reputation: 11

TCHAR * is a pointer so why cant you just do TCHAR * sName[20480]?

Upvotes: 1

Related Questions