3

So I have two programs here,

the first one is using dynamic allocation and the second one is using fixed sized array.

Now the question is, by using dynamic allocation, the program runs fine AND outputs are correctly printed as expected.

However, when using fixed sized array (the second program), the program runs without errors BUT the outputs are not what I wanted.

The programs are almost same except how the arrays are created..but still both the arrays are same so shouldn't outputs be the same? What are the reasons?? Please help me understand..

First Program Example:
input1      output1
    1            1
    2            2
    3            3
    4            4
    5            5

Second Program Example:
input1      output1
    1            1
    2            5
    3   2058618480
    4        32766
    5            5
// Using Dynamic Allocation
#include <iostream>

int *readNumbers(int n) { 
    int *a ;
    a = new int[n];

    for (int i=0; i<n; i++) {
        std::cout << "enter for a["<<i<<"]: ";
        std::cin >> a[i];
    }

    int *ptr;
    ptr= &a[0];

return ptr;
}


void printNumbers(int *numbers,int length){

    for (int i=0; i<length; i++) {    
    std::cout  << *(numbers+i) << "\n";
    }
} 


int main(){
    int n;
    std::cout << "enter for n: " ;
    std::cin >> n;  

    int *ptr; 
    ptr = readNumbers(n);
    printNumbers(ptr,n);

    delete [] ptr;    
    ptr = NULL;
return 0;
}

And another one is

// Using fixed size array
#include <iostream>

int *readNumbers(int n) { 
    int a[5]={};    

    for (int i=0; i<5; i++) {
        std::cout << "enter for a["<<i<<"]: ";
        std::cin >> a[i];
    }

    int *ptr;
    ptr = &a[0];
return ptr;
}


void printNumbers(int *numbers,int length){

    for (int i=0; i<length; i++) {    
    std::cout << *(numbers+i) << "\n";
    }
} 


int main(){
    int *ptr; 
    ptr = readNumbers(5);
    printNumbers(ptr,5);
return 0;
}
0

2 Answers 2

1

In your second piece of code your array is allocated on the stack inside the readNumbers function. Then you return a pointer to that stack memory to the calling function. This memory is no longer valid when printNumbers is run. It has likely been overwritten by locals in printNumbers.

Allocate the array in main and then the second example should also work.

Sign up to request clarification or add additional context in comments.

2 Comments

So does that mean in the first piece of code, the array is not allocated on the stack inside the function? But if this is the case, how so??
In this first function the array is allocated on the heap, only the pointer to the memory is stored on the stack. That pointer is then passed back to main via 'ptr'. That memory on the heap is valid until delete is called.
1

I feel in first case, when you call new operator to allocate memory for storing multiple int values, heap memory is allocated. Now this memory is available when you pass it around functions and this memory is valid till programming is running until someone calls delete operator. So you could pass this pointer from readNumbers, main and printNumber and it is valid.

For second case you created array of int as local variable in function, so it is created in stack. Scope of the local variable is only till the function is running. In your example readNumbers created array and once the function is over the stack is cleared. That is all the local variables created in function are no longer valid. Hence when you use this memory location in other functions like main and printNumbers it will give undefined behaviour. Sometime the result will be expected sometimes invalid result. So you need to be careful what are you passing or returning from one function to another.

If you still want to get expected result in second case, declare arrray as static.

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.