简体   繁体   中英

Run-Time Check Failure #2 - Stack around the variable 'ap' was corrupted

I ran into above problem when I ran following little piece of code in visual C++ 2010 Express.

When I used CodeBlocks, inner for loop couldn't be executed completely because of line (A).

Couldn't figure out why. Thanks for help!

int main()
{
    int* ap[10];
    for(int j=0;j<10;j++){
        *(ap+j) = new int[10];
        for(int i=0;i<10;i++){
            *((ap+j)+i) = *(ap+j)+i;//(A)
            **((ap+j)+i) = j * 10 + i;
            cout<<setw(6)<<**((ap+j)+i);
        }
        cout<<endl;
     }
     return 0;
}

This line

*((ap+j)+i) = *(ap+j)+i;//(A)

can be rewritten as

ap[j+i] = ap[j]+i;//(A)

and you can clearly see this can write out-of-bounds when j+i > 10.

You probably meant ap[j][i] or equivalently *(*(ap+j)+i) .

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