user2468893 user2468893 - 1 year ago 72
C++ Question

pointer in function scope crash

I was trying to do some naughty things in class and got a crash which i couldn't solve. I believe it is caused by trying to read unallocated data, even though I think the data should be allocated and filled. help..?

void read(int &n, int &m, double ** arr){
fstream f1;"1.txt"); //open a file to read the data from it

arr = new double *[n];//create an array of pointers (double)

for(int e = 0; e<n; e++){
arr[e] = new double[m]; //assign arrays of doubles to each pointer in the array
for(int l = 0; l < m; l++){
arr[e][l]= 0.f; //set it to 0
for(int e = 0; e<n; e++){
for(int s = 0; s<m; s++){
f1>>arr[e][s]; //read it from file
cout<<arr[3][4]<<"\n"; //prints out fine (the last number in my test matrix)

int main(){
double ** matrix;
read(n, m, matrix); //fills the matrix
cout<<matrix[0][0]; //crashes the program

return 0;

Answer Source

You are sending matrix as parameter, it is being copied by value to arr. Then in read() memory is allocated and processing is done. When read() ends, it just destroys arr pointer i.e. which is not matrix exactly, now we are back in main() and matrix is still non-allocated (nullptr in debug mode). Return arr from read() to main() and store it in matrix. Return type of read() should be double** in this case. Do not forget to delete matrix properly in main() then.


A pointer has physical memory in RAM. matrix has its own physical memory, call it 0xAAAA and arr has its own memory in RAM, call it 0xBBBB. When matrix is passed to read(), a new double pointer is created in RAM which is not same as matrix, this new pointer is known by arr in your case. To confirm it, use cout << &matrix; and cout << &arr; and you'll see they are at two different locations. Now when read() is called, the contents of matrix are copied to arr after its creation. At the time of calling read(), matrix is null i.e. points to 0x0000 location, contents copying mean now arr points to same location which is 0x0000 or null. Confirm it by using cout << matrix; and cout << arr and the results will be same. Now you allocate new memory for arr. matrix does not know about this memory, it still is pointing to 0x0000. When read() ends, arr is destroyed, but not contents of arr. The memory which was allocated using new keyword is now pointed by no pointer. When control gets back to main() after read() ends, matrix is still pointing to 0x0000. You want to access it and get error. Now there must be a way by which you can point matrix to memory allocated by arr or else it will be a memory leak. There are a number of ways, 1 of them is to return contents of arr, other is to allocate memory inmain(), process usingread()and again access memory afterread()` ends.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download