Connecting Tech Pros Worldwide Help | Site Map

Fix the bug by returning a pointer to an array allocated on the free store(heap)??

Newbie
 
Join Date: Nov 2009
Posts: 2
#1: 2 Weeks Ago
Could anyone please help me on this. it would be helpful if someone gave me the answer but more importantly if someone explained how they came to that answer please. here is the code:

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. void someFunction()
  7. {
  8.  
  9.     /*const int DATASIZE = 50000;
  10.     int data[DATASIZE];
  11.     for (int i =0; i < DATASIZE; i++)
  12.     {
  13.         data[i] = 99;
  14.     }*/
  15.  
  16. };
  17.  
  18. int* createAndFillArray()
  19. {
  20.     int somedata[2000];
  21.     int myarray[10];
  22.  
  23.     for (int i = 0; i < 10; i++)
  24.     {
  25.         myarray[i] = i * 10;
  26.  
  27.     }
  28.     return &myarray[0];
  29. }
  30.  
  31. int main(int argc, char* argv[])
  32. {
  33.     int *nums;
  34.     nums = createAndFillArray();
  35.  
  36.     someFunction();
  37.     cout << "Array Elements" << endl;
  38.  
  39.     for (int i = 0; i < 10; i++)
  40.     {
  41.         cout << nums[i] << " ";
  42.     }
  43.  
  44.  
  45.  
  46.     cin.get();
  47. }
best answer - posted by Banfa
In int* createAndFillArray() you return a pointer to a local variable. That variable will be on the stack (in most platforms) and will be deleted when the function exits so you return a pointer to an object that has been deallocated. As soon as you use the pointer to undefined behaviour is invoked and things can start going wrong.

int* createAndFillArray() needs to return a pointer to an object whose lifetime will extend behond the lifetime of the function, such as data allocated by malloc. However is malloc is used you need to remember to call free at a later time or you will have a memory leak.
Banfa's Avatar
AdministratorVoR
 
Join Date: Feb 2006
Location: South West UK
Posts: 6,148
#2: 2 Weeks Ago

re: Fix the bug by returning a pointer to an array allocated on the free store(heap)??


In int* createAndFillArray() you return a pointer to a local variable. That variable will be on the stack (in most platforms) and will be deleted when the function exits so you return a pointer to an object that has been deallocated. As soon as you use the pointer to undefined behaviour is invoked and things can start going wrong.

int* createAndFillArray() needs to return a pointer to an object whose lifetime will extend behond the lifetime of the function, such as data allocated by malloc. However is malloc is used you need to remember to call free at a later time or you will have a memory leak.
Newbie
 
Join Date: Nov 2009
Posts: 2
#3: 2 Weeks Ago

re: Fix the bug by returning a pointer to an array allocated on the free store(heap)??


I kind of understand now what you mean, but which part of that code will extend beyond the lifetime of the function to which isnt in the two fucntions in that code?.

sorry if im a slow learner. Thank you for your help aswell
Moderator
 
Join Date: Mar 2007
Location: North Bend Washington USA
Posts: 5,363
#4: 2 Weeks Ago

re: Fix the bug by returning a pointer to an array allocated on the free store(heap)??


The whole idea of variables existing foir various lengths of time is based in the concept of scope.

There are various kinds of scope but the one causing the problem is is called block scope. That is, the code between a pair of braces. The rule is any variable created between a pair of braces ceases to exist when the execution of the program passes beyond the closing brace.

In a function, all variables cease to exist when the function completes. This also includes the variables used as arguments. Remember, a copy is created of a variable used as an argument to a function.

This is why returning the address of a variable inside a function never works.

In this code:

Expand|Select|Wrap|Line Numbers
  1. int* MyFunction(args...)
  2. {
  3.     int * ptr = new int;
  4.     return ptr;
  5. }
ptr is a local variable and cannot be returned. Yet it appears to be returned. Like argument variables are copies of the variables actually used in the calling function, a returned variable is a copy of the variable inside the function. Here the compiler makes a copy of ptr and returns the copy. The actual ptr ceases to exist after the closing brace.

So this is valid:

Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.     int* ptr = MyFunction(args....);
  4. }
The ptr in main() is not the ptr in MyFunction. Here the copy of the return variable in the function is assigned to the ptr variable in main(). Then the compiler deletes the copy.

Various compilers implement the process differently, but the logical concept is always true.
Expert
 
Join Date: Mar 2008
Location: Naperville, Illinois U.S.
Posts: 828
#5: 2 Weeks Ago

re: Fix the bug by returning a pointer to an array allocated on the free store(heap)??


Quote:

Originally Posted by weaknessforcats View Post

The rule is any variable created between a pair of braces ceases to exist when the execution of the program passes beyond the closing brace.

In a function, all variables cease to exist when the function completes.

Pedantic note: this is true except for variables declared with the static keyword. This keyword gives the variable static scope, causing the variable to persist even after execution flows out of the block or function.

An initializer on a block-scope variable is assigned every time execution flows into the block. An initializer on a static-scope variable is only assigned once, prior to the start of program execution.
Moderator
 
Join Date: Mar 2007
Location: North Bend Washington USA
Posts: 5,363
#6: 2 Weeks Ago

re: Fix the bug by returning a pointer to an array allocated on the free store(heap)??


Quote:

Originally Posted by donbock

static keyword. This keyword gives the variable static scope,

The static keyword defines linkage and not scope.

Case A:

A global static variable.

This is the same as a normal global variable except the linkage is internal instead of external. That is, the variable is inaccessible outside the current implementation file. extern statements in other implementation files result in compiler errors.

Case B:

A function static variable.

This is not a local variable. It's not on the stack. It's a static global variable restricted to this function. It is declared in the function but depending upon your compiler it will be created (defined) before the program starts or, possibly, on the first call.
Expert
 
Join Date: Mar 2008
Location: Naperville, Illinois U.S.
Posts: 828
#7: 2 Weeks Ago

re: Fix the bug by returning a pointer to an array allocated on the free store(heap)??


Quote:

Originally Posted by weaknessforcats View Post

The static keyword defines linkage and not scope.

Thanks. I keep mixing linkage and scope together.
Reply