5

I have the following code:

int main(int argc, char** argv)
{
    char* p = new char[11];
    strcpy(p, "1234567890");
    cout << strlen(p) << endl;
    delete[] p;
    return 0;
}

It allocates 11 bytes and then copies a string of 10 bytes plus a nul terminator. It seems pretty correct to me.

But if I run it with Valgrind I get this:

bash-4.3$ valgrind ./a.out ... ==44295== Command: ./a.out ==44295== ==44295== Invalid read of size 8 ==44295== at 0x3E6073382F: __strlen_sse42 (in /lib64/libc-2.12.so) ==44295== by 0x4008A9: main (in /bb/mbig_new2/mbig3978/bbgithub/tsacqdata/tsacqdata/unit_test/Cache/a.out) ==44295== Address 0x4c2d048 is 8 bytes inside a block of size 11 alloc'd ==44295== at 0x4A06FE8: operator new[](unsigned long) (vg_replace_malloc.c:363) ==44295== by 0x40087E: main (in /bb/mbig_new2/mbig3978/bbgithub/tsacqdata/tsacqdata/unit_test/Cache/a.out) ...

Why doesn't Valgrind like that strlen call?

imreal
  • 10,178
  • 2
  • 32
  • 48
  • 3
    I agree. Your code is absolutely fine. (For other folk reading this, `strcpy` **does** copy the NUL.) – Bathsheba Mar 13 '18 at 16:50
  • 1
    I have a vague memory of some standard functions like `strlen` doing odd memory reads to be more efficient. Since the compiler knows what the function is really doing there's no UB. Valgrind is likely picking this up and not ignoring it like it should. Of course I could be way off so this is just a comment. – Kevin Mar 13 '18 at 16:52
  • Cannot reproduce. What compiler are you using? – Baum mit Augen Mar 13 '18 at 16:53
  • @BaummitAugen `gcc version 5.3.1 20160406 (Red Hat 5.3.1-6) (GCC)` – imreal Mar 13 '18 at 16:54
  • https://bugs.kde.org/show_bug.cgi?id=286864 is it linked? – Smit Ycyken Mar 13 '18 at 16:56
  • 2
    Probably a dupe of [strdup invalid read of size 4 when string literal is ending with newline \n](//stackoverflow.com/q/35021713) – Baum mit Augen Mar 13 '18 at 16:58
  • Relevant Redhat bug: https://bugzilla.redhat.com/show_bug.cgi?id=678518 – Baum mit Augen Mar 13 '18 at 17:00
  • @BaummitAugen It seems like that could be the problem. Mark it as a duplicate or add an answer if you think it is different enough and I will accept it. – imreal Mar 13 '18 at 17:01
  • Dupe it is. Btw, it does appear that either glibc or valgrind fixed this, as it does not occur with my gcc 7.3 / glibc 2.26 and valgrind 3.13. – Baum mit Augen Mar 13 '18 at 17:03

0 Answers0