调用malloc之后,我得到了意外的大小 [英] After calling malloc I get an unexpected size
问题描述
我有此代码:
char* str = (char*)malloc(27);
int num = strlen(str);
我已经在debag模式下运行了程序,并且看到num等于40.为什么?为什么不27?
I have run the program in the debag mode and I have seen that num is equals to 40. why? why not 27?
推荐答案
因为 malloc()
不会初始化分配的内存(即使将它清零也无济于事)和
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. */
这篇关于调用malloc之后,我得到了意外的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!