As to why returning
buffer
didn't work:
1 2 3 4
|
int someFunc(){
int a = 1;
return a;
}
|
When this function is called, it creates the variable
a
on the stack. Then it grabs the value of
a
, destroys
a
, and sends the value to whoever called the function.
1 2 3 4
|
int* someFunc() {
int a[20] = {0};
return a;
}
|
This will create 20 variables in consecutive memory. The address of the first variable is stored in
a
(
a
is actually a pointer). When we
return
, we grab the value of
a
(the address of the first element), free up all of that memory just like in the first case, then send the address of
a
to whoever called the function.
The problem is, we just sent the address of memory which has been freed. Nothing exists at that address anymore!
A work-around? (Not a good idea, but this is for the purpose of explanation):
1 2 3 4
|
int* someFunc(){
int* a = new int[20];
return a;
}
|
The new keyword allocates the memory on the heap instead of the stack. The difference is that the memory is not freed automatically when
a
goes out of scope. It will do exactly what you wanted above. Now here's the problem: this memory will NEVER be freed unless you explicitly
delete[]
it. It means that you have to start manually managing memory allocation which adds a layer of complexity that is best not to go into. Use "pass by reference" methods as suggested by people above.