简体   繁体   中英

Two conflicting for loops within a for loop within a function

I have two for loops inside of a for loop, like this:

for(n = 0; n < 5; ++n){


    for(i = 0; i < 5; ++i){ printf("in first loop");}  


    for(p = 0; p < 5; ++p){printf("in second loop");}   

}

Ive simplified them to the above to try to figure out whats going wrong. When I remove one of the loops, everything runs fine with the other loop. When I leave them both together, the program crashes. Now they happen to be inside of a function, which I know is directly related to the issue, because on its own the entire for loop runs fine. This is the rest of the function, located above the loop:

ArrayList* levels = allocDArray(1, sizeof(ArrayList));
levels->printerFunction = &printArray;
int* curlevel; *curlevel = -1;

getPositions(tree->root, levels, curlevel);

ArrayList* tempArray = allocDArray(1, sizeof(int));
ArrayList* curList;

when I comment out the 3 function calls and the reference to levels, the loop will run. If I leave all the function calls in, and just remove one of the two for loops within the initial for loop, everything runs fine as well. I just can not see how having one more generic loop inside of this for loop is not compatible with these function calls, they do not seems related at all.. Any advice would be appreciated..

You declare curlevel as int* , that means it is a pointer that points to memory containing an integer, but you don't initialize the pointer. That means that it just points anywhere random.

Next you assign -1 to that place in memory where curlevel points to. Since curlevel doesn't point anywhere specific, anything can happen ("undefined behavior"). In your case you try to access memory that isn't yours and get a segmentation fault.

Instead you should either simply use an integer, not a pointer to one:

int curlevel = -1;
getPositions(tree->root, levels, &curlevel);

Or, if you have special reasons why that needs to be a pointer, allocate some memory dynamically that can be used to store the integer:

int *curlevel = malloc(sizeof(int));
*curlevel = -1;
getPositions(tree->root, levels, curlevel);

Later, when that memory is no longer needed, you would free it again:

free(curlevel);

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