0

I have this code:

char* str = (char*)malloc(27);
int num = strlen(str);

I have run the program in the debag mode and I have seen that num is equals to 40. why? why not 27?

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
user2320928
  • 279
  • 1
  • 7
  • 17
  • In C++ you should use new, not malloc. Also I would suggest using either std::string or std::vector as opposed to a dynamic array. – Borgleader Jul 04 '13 at 17:19
  • 3
    Really tempted to -1 for your original title. Whenever a library function is behaving strangely, your first thought should be "How am I using it wrong?" not "the library is broken". – Ben Voigt Jul 04 '13 at 17:22
  • If you had looked at the documentation for those two functions the answer would have been obvious. – Ed S. Jul 04 '13 at 17:25

1 Answers1

7

Because malloc() does not initialize the memory allocated (even it did zeroise it it wouldn't help here) and strlen() depends upon the existence of a null terminating character. strlen() will stop counting only when it encounters a null terminating character, in this case it was 13 bytes after the allocated memory (reading somewhere it should not be). strlen() does not obtain the sizeof an array or the number of bytes allocated from a malloc() (or any other dynamically allocating function). For example:

char buf[32] = "hello";   /* Implicit null terminating character after 'o'. */
assert(5 == strlen(buf)); /* It does not equal 32. */
hmjd
  • 120,187
  • 20
  • 207
  • 252