I´m getting a segmentation fault with a pointer when it´s declared as local. The program is too long to copy it here, but it´s something like this:
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");
}
the puts(“Finish”); is executed, but i get a segmentation fault after this.
If I declare p as global, before the funcion, it works perfectly without the fault and this problem gets solved but I dont know why is this happening.
Running the debugger I can´t see where the problem is, all values seem ok. This is the trace after the fault:
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 () from /lib64/libc.so.6
#4 0x0000000000400ce9 in _start ()
Just in case it can be an issue, it´s an multiprocess application (fork, execv, etc…)
Thanks in advance for your answers
Looks like you don’t bother to initialize
p— with a global var it will be implicitly initialized to 0, but a local var is not. So you end up calling realloc/free with a random garbage pointer that corrupts the heap and causes a later crash…Initialize
pand that should fix it.