strlen returns incorrect value when called in gdb

Posted by alesplin on Ask Ubuntu See other posts from Ask Ubuntu or by alesplin
Published on 2011-02-18T18:31:34Z Indexed on 2011/02/18 23:34 UTC
Read the original article Hit count: 202

Filed under:
|
|

So I'm noticing some severely incorrect behavior from calls to standard library functions inside GDB. I have the following program to illustrate:

#include <stdio.h> 
#include <stdlib.h>
#include <string.h> 

int main(int argc, char *argv[]) {
  char *s1 = "test";
  char *s2 = calloc(strlen("test")+1,sizeof(char));

  snprintf(s2,strlen("test")+1,"test");

  printf("string constant: %lu\n", strlen(s1));
  printf("allocated string: %lu\n", strlen(s2));

  free(s2);

  return 0;
}

When run from the command-line, this program outputs just what you'd expect:

string constant: 4
allocated string: 4

However, in GDB, I get the following, incorrect output from calls to strlen():

(gdb) p strlen(s1)
$1 = -938856896
(gdb) p strlen(s2)
$2 = -938856896

I'm pretty sure this is a problem with glibc shipped with Ubuntu (I'm using 10.10), but this is a serious problem for those of us who spend lots of time in GDB.

  1. Is anyone else experiencing this kind of error?

  2. What's the best way to fix it? Build glibc from source? (I'm already running a version of GDB built from source)

© Ask Ubuntu or respective owner

Related posts about programming

Related posts about debugging