0

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;
    }
JeffR
  • 765
  • 2
  • 8
  • 23
  • what is tcalloc? I can't find any references to it. Anyway, sKeys[20480] will definitely take up space, but not on the heap. – jerry Mar 27 '13 at 16:09
  • tcalloc:#define tcalloc(nCharacters) (TCHAR*)calloc(nCharacters,sizeof(TCHAR)) – JeffR Mar 27 '13 at 17:45

2 Answers2

1

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

0

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.

Michael Wu
  • 1,177
  • 1
  • 13
  • 34
  • How do I make sKeys use the heap instead of the stack? – JeffR Mar 27 '13 at 17:24
  • 2
    @JeffR Define the struct [`struct sArray{TCHAR *sName;};`], have a pointer defined [`struct sArray *sKeys = NULL;`], and calloc it once you know how many you need [`sKeys = calloc(dwStringsFound,sizeof(*sKeys));`]. Then free the memory [`free(sKeys); sKeys = NULL;`] at the end. Note that the dereference of the `NULL` valued `sKeys` is not undefined behavior in the context of sizeof, but would be otherwise. You should also be doing error checking on the return value of `calloc`. – jerry Mar 27 '13 at 18:53