Was I just lucky that malloc returned a zero-filled buffer?
I tried running the code below:
int main(){
char *ptr = (char*)malloc(sizeof(char)*20);
ptr[5] = 'W';
ptr[0] = 'H';
std::cout<<ptr<<std::endl;
return 0;
}
When I use GCC 4.3.4 and I get "H" as output. The book C Programming Language by K开发者_运维知识库ernighan & Ritchie says malloc() returns uninitialized space, in which case the output should have been some undefined value. Is my output just a result of a coincidence of ptr[1] being '\0'?
Yes, it's just a coincidence. Don't rely on it.
It may be coincidence, or it may be an feature of your particular system's memory allocator, it is certainly not a language or library requirement to initialise dynamically allocated memory.
Don't confuse non-deterministic with random, even if the memory is uninitialised, the chances of that byte being zero are probably far greater than 1/256 due to typical memory usage patterns. For example open up a memory window in your debugger on ptr
and scroll through the adjacent memory in either direction, you are likely to to see zero rather a lot.
It's platform (and compile mode) dependent, eg in debug compile might get filled with some pattern, like 0x55 0xaa 0x55, in production you might get 0x00-s, or any memory garbage. So yes, you might declare it as a conincidence. You might easily got a bus error (or invalid memory access), as your string is not always terminated.
Yes. But be careful in terminology, ptr[1] is int 0, not a pointer.
精彩评论