Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to return an array created in a local function through pointers to the main function. My code is below. The array is returned and I am able to access each element by element once only. The next time it is giving garbage values. What is Wrong?

void DoWork(int** ppOut , int& nSize)
{
    int m[5];
    for(int i = 0 ; i < 5 ; i++)
        {
            m[i] = i;
        }

    nSize = 5;
    cout << m[0] << endl;
    cout << m[1] << endl;
    cout << m[2] << endl;
    cout << m[3] << endl;
    cout << m[4] << endl;

    *ppOut = &m[0];

    //delete [] m;
}

void main()
{
    int nSize = -1;
    int i;
    int* f = NULL; 

    DoWork(&f , nSize);

    cout << f[3] << endl;
    cout << f[0] << endl;
    cout << f[2] << endl;
    cout << f[3] << endl;
    cout << f[4] << endl;

    _getch();
}

Output is:-- 0 1 2 3 4 from local function. But in main 3 and rest are grabage values

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
193 views
Welcome To Ask or Share your Answers For Others

1 Answer

The Problem:
The array m is a local array which does not exist beyond the lifetime of the function DoWork(). When you do so what you end up with is Undefined Behavior, which basically means that you can see any observable behavior because the program ceases to be a C++ standard approved program and so it can show(literally) any behavior.

The Solution:
You will need to extend the lifetime of m so that it is still valid even after the function returns. There are number of ways to do this:

  • Create an array before the function & pass a pointer to it to the function.
  • Create a static array inside the function.
  • Use dynamic memory for the array in function (do remember to release it after usage)
  • Use global array which can be poulapted inside the function.

Each has own pros and cons and its more of horses for courses.

On a side note, void main() is not the standard specified prototype for main() it should return an int:

int main()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...