Question

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;
    }
Was it helpful?

Solution 2

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top