views:

548

answers:

4

I have been facing a weird issue in a piece of code.

void app_ErrDesc(char *ps_logbuf, char *pc_buf_err_recno)
 {
    char *pc_logbuf_in;
    char rec_num[10];
    char *y = "|";
    int i, j;

    memset(rec_num, 0, sizeof(rec_num));
    memset(pc_buf_err_recno, 0, LOGBUFF);
        .....
        .....
 }

For some reason the first memset call sends a SIGSEGV. Whats more strange is when inside gdb the same line executes for about 30 times though the function is called only once and there are no loops inside! Here's a piece of gdb session.

7295            /*Point to logbuffer string*/
(gdb)
7292            memset(rec_num, 0, sizeof(rec_num));
(gdb)
7295            /*Point to logbuffer string*/
(gdb)
7292            memset(rec_num, 0, sizeof(rec_num));
(gdb) n
7295            /*Point to logbuffer string*/
(gdb)
7292            memset(rec_num, 0, sizeof(rec_num));
(gdb)

Program received signal SIGSEGV, Segmentation fault.

I have also tried running the program through valgrind's memcheck tool but not getting anything significant about the above piece of code.

The file that I'm parsing has just one record.

Any pointers are appreciated. Thanks.

+1  A: 

i suspect the call to the function, so ensure the call is not something like

char pc_buf_err_recno[SMALLER_THAN_LOGBUFF];
char ps_logbuf[TOO_SMALL]
app_ErrDesc(ps_logbuf, pc_buf_err_recno);
Peter Miehle
+2  A: 

It's likely that it's the second memset and the reason is that the outer function is called with an insufficient buffer size. Debuggers can show incorrectly where you are. Try to add logging after each step to find out what exactly crashes.

sharptooth
A: 

Debuggers can be incorrect, particularly if you're getting SEGV. Remember, it's quite possible you've trashed the stack when you get a segmentation fault and the debugger will get confused if that happens.

It's also quite possible the calling function has made a mess, not the current one.

Adam Hawes
+1  A: 

Whats more strange is when inside gdb the same line executes for about 30 times though the function is called only once and there are no loops inside!

This sounds symptomatic of having compiled with optimizations. You may have an easier time pinpointing the problem in GDB if you compile with optimizations turned off.

Miles