内存分配与Segmentation fault

为了方便使用,我做了如下结构体的嵌套使用:

struct operation{
int num;
char name[100];
char owner[100];
char msg[100];
};

struct collect{
int num;
char name[100];
char owner[100];
char msg[100];
struct operation operations[100];
};

struct list{
int num;
char name[100];
char owner[100];
char msg[100];
struct collect collects[100];
};

 

而后在main中做如下的使用:

struct list lists[100];

编译没有任何问题,在执行时报错:Segmentation fault 即段错误,一般是对内存的非法使用导致的

我将所有代码注释掉,只剩下这一个申明,结果依然报错

于是怀疑是申请的内存过大,超出了限制

后查到:局部变量是放在栈的,而linux对栈的使用有限制,可通过ulimit -s查看和更改

后做实验:调整局部变量的大小和栈使用限制,发现确实如此

结论:对于大数据,不能使用栈分配,可以考虑静态区和堆区,例如:1)定义为全局变量、2)定义为static变量、3)使用malloc动态分配

posted @ 2014-08-15 10:38  布兰姥爷  阅读(1151)  评论(0编辑  收藏  举报