Why does this give a segmentation fault?
I'm stunned, why does this code give me a segmentation fault?
#include <stdio.h>
#define LIMIT 1500000
typedef struct {
int p;
int a;
int b;
} triplet;
int main(int argc, char **argv) {
int i;
triplet triplets[LIMIT];
for (i = 0; i < LIMIT; i++) {
triplets[i].p = 9; // remove this line and everything works fine
}
printf("%d\n", triplets[15].p);
return 0;
}
EDIT: After changing LIMIT to 150 I no longer get a segmentation fault, it prints random numbers instead.
EDIT2: Now I know what the site name stands for :) I made the array global a开发者_Python百科nd everything works fine now.
Stack overflow! Allocating 1500000 records at 12 bytes per record (assuming 4-byte int
), requires more than 17 MB of stack space. Make your triplets
array global or dynamically allocate it.
As to your edit - shrinking the array will probably stop the stack overflow, but your printf()
call will still print uninitialized data - triplets[15].p
could be anything at the time you print it out.
When you do
triplet triplets[LIMIT];
you're allocating that on the stack. Which is apparently too big for your system.
If you do
triplet* triplets=(triplet*)malloc(LIMIT*sizeof(triplet));
you'll allocate it on the heap and everything should be fine. Be sure to free the memory when you're done with it
free(triplets);
精彩评论