简体   繁体   中英

Consistent Seg Fault from assigning a 2d heap array in C

I am creating a 2D array like this

int** B = calloc(16, sizeof(int*));

for(int i = 0; i <= 16; i++){

B[i] = calloc(16, sizeof(int));

}

then i am passing B to a function which calls for a Parameter int**. This function then calls another function which calls for an int** so B is once again passed.

I am able to do this B[1][1]++;

but when I try to

B[1][0] = 1; 

I get a segmentation fault.

I have tried so many things and nothing has made it go away.

Edit: Solved!

Ended up being my passing the array B to a function using &B instead of just B that caused the issue, though I implemented the changes suggested below before fixing this error, so possible that I would have run into this out of bounds problem next.

In the for loop, you have the condition as i <= 16 and you have only allocated 16 * size of int*. Hence, you're going out of bounds of your allocated space.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM