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?
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?
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. */