If I dereference an illegal address in C I get SIGSEGV with valid gdb backtrace. But if I pass it to snprintf backtrace is trashed

Viewed 289

In my x86-64 Linux program I deliberately do:

char *ptr = 0x3e8;
int x = *(int *)ptr;

When I run it in gdb the process crashes due to SIGSEGV and prints a valid backtrace. If I do instead:

char s[16]; 
snprintf(s, 16, "%s\n", ptr);

The process still crashes but the backtrace is trash:

(gdb) bt
#0  0x00007ffff5da15c7 in ?? ()
#1  0x00007ffff5c704d3 in ?? ()
#2  0x0000000000000000 in ?? ()

My example may look contrived but my production code is crashing in snprintf() in exactly the same way. I've compiled with -g -O0.

1 Answers

The process still crashes but the backtrace is trash

When I build this test:

#include <stdio.h>

int main()
{
  char *ptr = (char *)0x3e8;
  char s[16];
  snprintf(s, 16, "%s\n", ptr);
  return 0;
}

Using gcc (Debian 9.3.0-3) 9.3.0 and GNU C Library (Debian GLIBC 2.30-4) stable release version 2.30., with libc6-dbg installed, I get:

Program received signal SIGSEGV, Segmentation fault.
__strlen_avx2 () at ../sysdeps/x86_64/multiarch/strlen-avx2.S:96
96      ../sysdeps/x86_64/multiarch/strlen-avx2.S: No such file or directory.
(gdb) bt
#0  __strlen_avx2 () at ../sysdeps/x86_64/multiarch/strlen-avx2.S:96
#1  0x00007ffff7e48756 in __vfprintf_internal (s=s@entry=0x7fffffffd8b0, format=format@entry=0x555555556004 "%s\n", ap=ap@entry=0x7fffffffda30, mode_flags=mode_flags@entry=0) at vfprintf-internal.c:1688
#2  0x00007ffff7e5a1f6 in __vsnprintf_internal (string=0x7fffffffdb10 "", maxlen=<optimized out>, format=0x555555556004 "%s\n", args=args@entry=0x7fffffffda30, mode_flags=mode_flags@entry=0) at vsnprintf.c:114
#3  0x00007ffff7e335a2 in __GI___snprintf (s=<optimized out>, maxlen=<optimized out>, format=<optimized out>) at snprintf.c:31
#4  0x0000555555555169 in main () at t.c:7

I suspect that you'll get similar result from this test case on a standard x86 Ubuntu 18.04, in which case you are not telling us the whole story, and an MCVE would help a lot to get you the real answer.

Related