char* str = (char*)malloc(100*sizeof(char));
strcpy(str, ""); //Does this line initialize str to an empty string?
在调用第一行后,分配的内存是否包含垃圾?调用第二行后呢?
char* str = (char*)malloc(100*sizeof(char));
strcpy(str, ""); //Does this line initialize str to an empty string?
在调用第一行后,分配的内存是否包含垃圾?调用第二行后呢?
malloc只提供内存空间,并创建指向该内存的指针,然后返回该指针。它不会进行初始化。如果之前有其他东西占用了相同的内存空间,您可能会得到一个垃圾值。
是的,malloc
返回未初始化的内存,而且是的,你的第二行代码将内存初始化为空字符串。
man malloc
会告诉你。 - cmaster - reinstate monicasizeof(char)
被标准定义为 1,乘以 1 对传递给 malloc() 的参数绝对没有影响。它只会使代码混乱不堪。 - user3629249calloc()
而不是malloc()
。在所有情况下,请检查(!=NULL)返回值以确保操作成功。在C中,不要强制转换返回值,因为它是一个void*
类型,所以可以赋给任何指针。强制转换返回值只会使代码混乱,并在维护时产生麻烦。 - user3629249