Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

c++ - Reading pointers twice is giving garbage values

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

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

1 Reply

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...