Reputation: 183
Program snippet :-
if((fd = open(buf_serv, O_RDONLY)) < 0) {
char c[MAXLEN+1];
snprintf(c, sizeof(c), ": can't open, %s\n", strerror(errno));
n = strlen(c);
...
gdb :-
102 if((fd = open(buf_serv, O_RDONLY)) < 0) {
(gdb) n
104 snprintf(c, sizeof(c), ": can't open, %s\n", strerror(errno));
(gdb) p sizeof(c)
$1 = 4097
(gdb) n
105 n = strlen(c);
(gdb) p strlen(c)
$2 = -1428323296
(gdb) n
...
Can anyone please tell me how come strlen is returning a negative number? (which is crashing my program with a sigsegv signal)
Thanks in advance all!
(gdb) l
101
102 if((fd = open(buf_serv, O_RDONLY)) < 0) {
103 char ch[MAXLEN+1];
104 write(STDOUT_FILENO, "foo", 3);
105 sprintf(ch, ": can't open, %s\n", strerror(errno));
106 n = strlen(ch);
107 write(writefd, ch, 100);
108 } else {
109 while((n = read(fd, buf_serv, MAXLEN)) > 0) {
110 write(writefd, buf_serv, n);
(gdb) p ch
$1 = ": can't open, No such file or directory\n", '\000' <repeats 4056 times>
(gdb) p strlen(ch)
$2 = -1428323296
Upvotes: 2
Views: 4220
Reputation: 10633
You dont need to use strlen since snprintf returns number of characters printed, if buffer was large enough to fit all characters including terminating \0
. Source provided by @Casey in comments (probably).
So make sure to check if returned value is not negative and is less then buffer size. Also check function documentation provided by your compiler, since implementations may vary.
Upvotes: -1
Reputation: 1
strlen()
returns the difference between strings on some compilers.
so if for example strlen("a","b")
is there then this will return 1;
while strlen("b"...
Note: original answer truncated
Upvotes: -3
Reputation:
It's just that you can't use GDB :P
(gdb) n
105 n = strlen(c);
(gdb) p strlen(c)
GDB shows the next line to be executed. So at the time you are printing n
, it's yet uninitialized. Write n <enter>
one more time before printing n
.
Upvotes: 8