Joy Joy - 7 days ago 5
C Question

Segmentation fault when running, but success when debugging

I have encountered a wired segmentation fault. I am developing a software in C using Eclipse CDT. When running my program on the terminal (Ubuntu 10, 64bits), it simply reports "Segmentation fault". However, when I debug using gdb in Eclipse, it goes to the end and the result is correct.

I understand that there could be many reasons for segmentation faults. And I am sorry that I am not able to show my code since I do not know where the problem could be...

But could anyone please help me, is there any situation that could happen as my case: segmentation fault on terminals, while fine in debugging? Thanks so much.




Thanks, all. I would spent some time learning valgrind. I just fixed the bug by replacing a malloc() by realloc(). The calling is followed by two memcpy. Is that the reason? Here is the snippet code:

bwa_seq_t *merge_seq (bwa_seq_t *s1, bwa_seq_t *s2) {
ubyte_t *seq1, *seq2, *tmp;
if (!s1 || !s2)
return 0;
seq1 = s1->seq;
seq2 = s2->seq;
tmp = (ubyte_t*) calloc (sizeof(ubyte_t), (s2->len + s1->len + 1));
memcpy(tmp, seq1, sizeof(ubyte_t) * s1->len);
memcpy(&tmp[s1->len], seq2, sizeof(ubyte_t) * s2->len);
s1->len += s2->len;
tmp[s1->len] = '\0';
s1->seq = tmp;
return s1;
}


Could anybody help explain why?

Answer

Try the following steps:

  • type ulimit -c unlimited in an xterm (this allows the creation of core/postmorterm files)

  • launch your program (and let it crash): a core file should now be present in the directory.

  • launch the debugger with gdb <yourprogram> <corefile>

  • type bt at gdb prompt to see on what line it did crash.

  • (optional) correct the error.