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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Narutodono
    New Member
    • Nov 2009
    • 6

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

    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:

    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    void someFunction()
    {
    
    	/*const int DATASIZE = 50000;
    	int data[DATASIZE];
    	for (int i =0; i < DATASIZE; i++)
    	{
    		data[i] = 99;
    	}*/
    
    };
    
    int* createAndFillArray()
    {
    	int somedata[2000];
    	int myarray[10];
    	
    	for (int i = 0; i < 10; i++)
    	{
    		myarray[i] = i * 10;
    		
    	}
    	return &myarray[0];
    }
    
    int main(int argc, char* argv[])
    {
    	int *nums;
    	nums = createAndFillArray();
    	
    	someFunction();
    	cout << "Array Elements" << endl;
    
    	for (int i = 0; i < 10; i++)
    	{
    		cout << nums[i] << " ";
    	}
    	
    	
    	
    	cin.get();
    }
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    In int* createAndFillAr ray() 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* createAndFillAr ray() 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.

    Comment

    • Narutodono
      New Member
      • Nov 2009
      • 6

      #3
      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

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        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:

        Code:
        int* MyFunction(args...)
        {
            int * ptr = new int;
            return ptr;
        }
        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:

        Code:
        int main()
        {
            int* ptr = MyFunction(args....);
        }
        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.

        Comment

        • donbock
          Recognized Expert Top Contributor
          • Mar 2008
          • 2427

          #5
          Originally posted by weaknessforcats
          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.

          Comment

          • weaknessforcats
            Recognized Expert Expert
            • Mar 2007
            • 9214

            #6
            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.

            Comment

            • donbock
              Recognized Expert Top Contributor
              • Mar 2008
              • 2427

              #7
              Originally posted by weaknessforcats
              The static keyword defines linkage and not scope.
              Thanks. I keep mixing linkage and scope together.

              Comment

              Working...