当它被声明为本地时,我正在用指针获得分段错误.程序太长了,无法复制到这里,但它是这样的:
void f(){
int* p;
int n = 0;
for (...) {
n++;
p = realloc(p, n * sizeof(int));
if (p == NULL) error();
}
//Code using the pointer
free(p);
}
int main() {
f();
puts("Finish");
}
Run Code Online (Sandbox Code Playgroud)
放置("完成"); 执行,但在此之后我得到了分段错误.
如果我将p声明为全局,在函数之前,它完美地运行而没有错误,这个问题得到解决,但我不知道为什么会发生这种情况.
运行调试器我无法看到问题所在,所有值似乎都可以.这是故障后的跟踪:
Program received signal SIGSEGV, Segmentation fault.
0x000000361206dbd1 in _IO_flush_all_lockp () from /lib64/libc.so.6
(gdb) bt
#0 0x000000361206dbd1 in _IO_flush_all_lockp () from /lib64/libc.so.6
#1 0x000000361206e725 in _IO_cleanup () from /lib64/libc.so.6
#2 0x00000036120334b2 in exit () from /lib64/libc.so.6
#3 0x000000361201d99b in __libc_start_main …Run Code Online (Sandbox Code Playgroud)