简体   繁体   中英

getting EXC_BAD_ACCESS error from clock() function

I have a very weird bug I just cannot resolve. I built a simple program to time a simple snippet of code

clock_t start, diff;
start = clock();
const int N = 1000;
int a[N][N];

for(int i=0 ; i<N ; ++i){
    for(int j=0 ; j<N ; ++j)
        a[j][i] = 0;
}

diff = clock()-start;
int msec = (int) diff*1000/CLOCKS_PER_SEC;
printf("time: %d milliseconds", msec);

I am running it on xcode (not sure if this matters) and it runs fine, but when I change N to 2000 I get an EXC_BAD_ACCESS (code 2, address = 0xfff5ecbd438) at the start = clock() line.

I am at a loss here since I have no idea how changing the array size should affect the clock() command.

Any ideas?

Most likely you've just blown the stack, by attempting to allocate far too large an array as a local variable.

2000 * 2000 * sizeof(int) is likely to be at least 16MB.

It crashes at that point because the array is declared right after, and that's when the stack allocation will occur.

You could move the array out the stack by making it global and/or static, but that's potentially a bit hacky and you might be better off using a std::vector, which will allocate and manage the memory properly.

It may give you some idea regarding the error . EXC_BAD_ACCESS it means you are trying to accessing the invalid pointer .

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