0

In some open source C code, I found a function that (I think) is assigning a pointer to point to an automatic variable which won't exist once the pointer is utilized:

static void TableCopy(void *tableBaseAddr, const unsigned int **tableOut, unsigned int *tableLengthOut)
{
    //First word in table is size
    unsigned int tableSize = ((unsigned int*)(tableBaseAddr))[0];

    //Read each word from the table and store in an array
    unsigned int tmpTable[tableSize];
    unsigned int i;        
    for (i = 0; i < tableSize; i++)
    {
        tmpTable[i] = ((unsigned int*)(tableBaseAddr))[i];
    }

    //Assign outputs
    *tableOut = tmpTable;   //Passing back the pointer to an automatic variable?
    *tableLengthOut = tableSize;
}

I couldn't think of a reason you would ever intentionally do this. Am I correct in that this code is doing something bad, or is there a possible reason you would do this?

user2913869
  • 481
  • 2
  • 5
  • 23
  • 2
  • Unless the caller never tries to access that array, yeah, it's broken. – Shawn Sep 27 '19 at 20:59
  • Agree that this is bad code and a recipe for disaster. With that out of the way, if `*tableOut` is used immediately after the function call, then on certain platforms it *might* work. This is because in some implementations, the C compiler may allocate `tmpTable[]` on the stack. If so, then the contents of that memory is still unchanged after `TableCopy` returns. You should *not* rely on this behavior. However, it may be that the code does in fact produce the desired result in special circumstances. "It works on my machine." :-) – Lee Jenkins Sep 27 '19 at 21:06
  • 1
    Please consider disclosing where you have found this gem. – n. m. could be an AI Sep 27 '19 at 21:12

0 Answers0