As you've discovered, allocating a variable on the stack and returning a pointer to that memory will likely result in garbage. The stack gets used and re-used with each series of function calls, so the memory allocated by your function will be re-used for different purposes by other function calls. You need to allocate the memory to be used outside of your function, either as a static allocation outside of any function, or else as a dynamic allocation. One way to handle this is:
#include <iostream>
#include <cstring>
using namespace std;
int * check (int leng)
{
const int r = leng;
int *x = new int [r];
memset(x, 0, r * sizeof(int));
return x;
}
main()
{
int * l = check(20);
for (int g=0; g<5; g++) cout << l[g] << ' ';
delete l;
}
Note that in check
the memory for l
is allocated dynamically with the new
operator, and in main
that memory is subsequently released with the delete
operator. Failure to do the latter will result in a memory leak; in this case the leak would be minor as it would only occur once, and the memory space for the program would be reclaimed when the program exited, but in general it's good to get in the habit of releasing any and all allocated memory.
Best of luck.