This is a dangerous bug lurking in your code. In C and C++ you are not allowed to
return a pointer to stack data in a function. It results in undefined behavior. I'll explain why.
A C/C++ program works by pushing data on and off the program stack. When you call a function, all the parameters are pushed onto the stack, and then all the local variables are pushed onto the stack as well. As the program executes it may push and pop more items onto and off the stack in your function. In your example, buffer is pushed onto the stack, and then t is pushed onto the
stack. The stack might look like,
- Previous Stack
- Parameters
- (other data)
- buffer (50000 bytes)
- t (sizeof pointer)
At this point, t is on the stack, and it points to buffer, which is also on the stack.
When the function returns, the runtime pops all the variables on the stack off, which
includes t, buffer and the parameters. In your case, you return the pointer t, thus
making a copy of it in the calling function.
If the calling function then looks at what t points to, it is going to find that
it points to memory on the stack that may or may not exist. (The runtime popped it
off the stack, but the data on the stack may still be there by coincidence, maybe not).
The good news is, it's not hopeless. There are automated tools that can search for
these kinds of errors in your software and report them. They are called static
analysis tools. Sentry is one such example of a program that can report this
kind of defect.