【发布时间】:2014-04-26 00:53:49
【问题描述】:
/*
从所有帖子中学习 - 如果我错了,请纠正我..
现在这很有意义-如果我没记错的话,堆栈是固定内存段-在程序启动时分配...而虚拟内存可以使用 malloc、realloc、free 以编程方式调整大小/大小... 结构指针数组 -
长尺寸 = 10000000; struct foo *bar[size];
应该从堆中分配 - 使用 malloc()... 而不仅仅是一个固定大小的堆栈(程序文本)
*/
这个 SIGSEV 的:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
struct foo {
int x;
char s[5];
};
long size = 10000000;
struct foo *bar[size];
long i = 0;
while (i < size) {
printf("%ld \n", i);
i++;
}
}
这个有效 - 注释掉 struct foo 指针数组:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
struct foo {
int x;
char s[5];
};
long size = 10000000;
//struct foo *bar[size];
long i = 0;
while (i < size) {
printf("%ld \n", i);
i++;
}
}
这个有效 - 评论我们的 while 循环:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
struct foo {
int x;
char s[5];
};
long size = 10000000;
struct foo *bar[size];
long i = 0;
while (i < size) {
//printf("%ld \n", i);
i++;
}
}
/* 我真正想要实现的是... SIGSEVS - 好的,谢谢你所有的回复,我真的很感激...... - 将查看 int 堆栈溢出并使用使用堆内存进行探索 - 谢谢大家 */
int main(void) {
struct foo {
int x;
char s[5];
};
long size = 10000000;
struct foo *bar[size];
long i = 0;
while (i < size) {
bar[i] = (struct foo *) malloc(sizeof(struct foo));
free(bar[i]);
i++;
}
return EXIT_SUCCESS;
}
【问题讨论】:
-
您的堆栈可能被限制为 8 MiB,因此当您尝试创建大于限制的本地数组时,您会崩溃。 while 循环的情况有点令人费解。编译器可能已经优化了所有内容。
-
你是对的人......应该避免在堆栈上使用这么大的块 - 而在这种情况下我应该使用堆...... tnx man
标签: c