Search code examples
c++linuxfuse

C++ strncpy parameters "optimized out"; overwrites random memory


First of all, I want to apologize for not being able to narrow down the problem enough to be able to share a short program that reproduces the bug.

An external library (FUSE) call to strncpy "randomly" overwrites a shared_ptr<mutex> in my code, which causes a segfault when I try to lock that mutex. I ran my program with valgrind and it didn't catch any memory errors (valgrind flags below). When I run my code in gdb and set a watchpoint on that shared_ptr, it breaks on the call to strncpy. gdb says that all of strncpy's parameters (dest, src, and nbytes) have been "optimized out", which makes me think it's using uninitialized memory for that call. Am I interpreting this correctly? Any idea what the cause could be?

Here's the stack trace from gdb when the pointer is overwritten:

#0  __strncpy_ssse3 () at ../sysdeps/x86_64/multiarch/strcpy-ssse3.S:2482
#1  0x0000003245809094 in strncpy (__len=<optimized out>, __src=<optimized out>, __dest=<optimized out>) at /usr/include/bits/string3.h:120
#2  add_name (buf=<optimized out>, bufsize=<optimized out>, s=<optimized out>, name=<optimized out>) at fuse.c:907
#3  0x000000324580997c in try_get_path (f=<optimized out>, nodeid=<optimized out>, name=<optimized out>, path=<optimized out>, wnodep=<optimized out>, need_lock=<optimized out>) at fuse.c:956
#4  0x000000324580a281 in get_path_common (f=<optimized out>, nodeid=<optimized out>, name=<optimized out>, path=<optimized out>, wnode=<optimized out>) at fuse.c:1152
#5  0x0000003245812432 in fuse_lib_unlink (req=<optimized out>, parent=<optimized out>, name=<optimized out>) at fuse.c:1198
#6  0x0000003245817057 in fuse_ll_process_buf (data=0x6f5650, buf=0x7fffffffd850, ch=<optimized out>) at fuse_lowlevel.c:2441
#7  0x000000324581388f in fuse_session_loop (se=0x6f8410) at fuse_loop.c:40
#8  0x000000324580b698 in fuse_loop (f=<optimized out>) at fuse.c:4309
#9  0x000000324581bb8f in fuse_main_common (argc=<optimized out>, argv=<optimized out>, op=<optimized out>, op_size=<optimized out>, user_data=<optimized out>, compat=<optimized out>) at helper.c:355
#10 0x000000000046f1b6 in main (argc=4, argv=0x7fffffffdec8) at ../src/fuse.cpp:100 

Here's the arguments I ran valgrind with:

valgrind --tool=memcheck --leak-check=yes --show-reachable=yes --num-callers=20 --track-fds=yes

Solution

  • This bug was the result of creating a shared_ptr with new, then typecasting it to a weak_ptr and deleting it.