Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning pointers c [duplicate]

Possible Duplicate:
Pointer to local variable
Can a local variable's memory be accessed outside its scope?

I have an interesting problem. I have a read function that returns a pointer:

char * myReadFunc() {   
    char r [10];
    //some code that reads data into r.
    return r;
}

Now, I call this function to assign info to some variables I have:

char * s;
//Some code to specify where to read from.
s = myReadFunc();

This produces results as I intended.

However, when I do this:

char * s1;
char * s2;
//Some code to specify where to read from.
s1 = myReadFunc();
//Some code to change the read location.
s2 = myReadFunc();

I get some odd results. The data is the same for both, and it is ALWAYS from the second specified read location.

So I tried some alternate code:

char * s1;
char * s2;
//Some code to specify where to read from.
char r [10];
//some code that reads data into r. IDENTICAL to myReadFunc().
s1 = r;
//Some code to change the read location.
s2 = myReadFunc();

This code produces results as I intended (s1 has data from one location, and s2 has data from another).

So, my question is, why did the latter code work, but the code above it did not? I my guess is that somehow my function was aliased to both variables, and since it was pointing to both, it reassigned both every single time it was called. Does anyone understand the full reason for this behavior?

like image 693
CodeLikeSpaghetti Avatar asked Dec 27 '22 20:12

CodeLikeSpaghetti


2 Answers

Your readFunc function doesn't work as you expect.

You're returning a pointer to an array that is only in scope in the body of your function. When the function exits, the array goes out of scope, and later attempts to access that memory invoke undefined behavior. It may appear to work under certain circumstances but is incorrect.

Instead, in readFunc, allocate the array on the heap using new or malloc:

// it is the responsibility of the caller to delete[] the
//    returned buffer, but prefer to use e.g. shared_ptr
char *myReadFunc()
{
    char *r = new char[BUFFER_SIZE];
    //some code that reads data into r.
    return r;
}
like image 163
pb2q Avatar answered Dec 29 '22 09:12

pb2q


There cannot be any defined behaviour for what you are trying to do because you are trying to acess the memory pointed by an array whose lifetime is over.

like image 36
nav_jan Avatar answered Dec 29 '22 09:12

nav_jan