Quote:
Originally Posted by
majid.merkava
How about allocating memory with alloca function? because it allocates memory from stack frame.
alloca memory's main advantage, and main problem, is that it's fairy gold -- it vanishes. When your function returns, anything it's allocated with alloca becomes invalid (and potentially overwritten with trash). This means you don't have to free it yourself -- but you can't return it, either. You can pass it
into a function, but can't pass it out of the function that allocated it.
alloca is fairly portable in one sense -- its convenience and (in some cases) performance advantage are tempting enough that you'll find it almost anywhere an implementation of it's even possible. But it's not actually defined by standard, and not actually possible everywhere. The long-standing flamewar over it is whether it should be considered a de-facto standard. Pros are it's simplicity and performance advantages. Its cons are potential bugs from implementations that don't do what you expect, limited stack memory, potential nonexistence if you port your code anywhere, and it not doing what you'd expect if you're used to malloc().
I think the best practice for returning a pointer is to take a pointer in the first place. Just use the memory you were given, then give it back. Where the memory came from and why becomes someone else's problem