I have void *, name it data, the length of which I know, but is not terminated by zero. I make such a call snprintf(line, sizeof(line), "%*s", n, (const char*)data), where nis the known length. It almost always works, but sometimes it leads to segfault.
Whenever segfault occurs, the backtrack says that the problem is inside strlen. And when I type datainside gdb, I see something like this
(gdb) p n
$1 = 88
(gdb) p (const char*) data
$2 = 0x1d752fa8
"JASDF" ... "ADS"<Address 0x1d753000 out of bounds>
(gdb) p 0x1d753000-0x1d752fa8
$3 = 88
dataindeed 88 characters, but not null, it actually seems to lie directly against the segment. I assume that snprintf is always called strlen on the data, and I was usually lucky that even if it was datanot null-terminated, before I hit the segment, there was \0, and then sometimes I was out of luck, and it is. It is right? If so, what kind of work?
This is what the stack trace looks like
EDIT . To answer my own question about work, strncpy is a more suitable function to call. I used snprintf out of habit.
source
share