初始化字符串(字符*)malloc的(0)和NULL之间的区别 [英] Difference between initializing a string with (char *)malloc(0) and NULL
问题描述
为什么分配大小为0 字符
在这种情况下块的工作?但是,如果我写的的char *字符串= NULL;
将无法正常工作
我在使用Visual Studio。
INT的main()
{
字符*字符串=(字符*)malloc的(0);
串[0] ='A';
字符串[1] ='B';
串[2] ='c'的;
串[3] ='D';
字符串[4] ='\\ 0'; 的printf(%S \\ n,字符串);
返回0;
}
首先让我的状态,按照该手册页的的malloc()
的
的malloc()
函数分配size个字节,并返回一个指向分配的内存。内存未初始化。 如果大小为0,则的malloc()
返回要么NULL
,或唯一指针值,以后可以成功传递到免费()
。
块引用>像
A调用malloc(0)
为有效本身,但后来,我们需要检查返回的指针的有效性。它可以是
- 返回
NULL
- 返回一个指针,它可以传递给
免费()
。但不管怎么说,取消引用该指针是不允许的。这将导致外结合的内存访问,并导致不确定的行为。
这是说,两个重要的事情提了,
请明白为什么不能投
的malloc的返回值()
和家人在C
。请检查返回值
的malloc()
使用前返回的指针。因此,要回答你的问题,
的初始化字符串
之差(字符*)malloc的(0)
和NULL 的
块引用>不要使用
的malloc(0)
在这种情况下,作为指针空支票的可能的失败,给了错误的IM pression内存指针的的有效的分配。始终使用NULL
初始化。Why allocating a 0 size
char
block works in this case? But if I writechar *string = NULL;
it won't work.I'm using Visual Studio.
int main() { char *string = (char *)malloc(0); string[0] = 'a'; string[1] = 'b'; string[2] = 'c'; string[3] = 'd'; string[4] = '\0'; printf("%s\n",string); return 0; }
解决方案First let me state, as per the man page of
malloc()
The
malloc()
function allocates size bytes and returns a pointer to the allocated memory. The memory is not initialized. If size is 0, thenmalloc()
returns eitherNULL
, or a unique pointer value that can later be successfully passed tofree()
.a call like
malloc(0)
is valid itself, but then, we need to check the validity of the returned pointer. It can either
- Return
NULL
- Return a pointer which can be passed to
free()
.but anyways, dereferencing that pointer is not allowed. It will cause out-of-bound memory access and cause undefined behaviour.
That said, two important things to mention,
Please see why not to cast the return value of
malloc()
and family inC
.Please check the return value of
malloc()
before using the returned pointer.So, to answer your question,
Difference between initializing a string with
(char *)malloc(0)
and NULLDo not use
malloc(0)
in this case, as a NULL check on the pointer may fail, giving the wrong impression of a valid allocation of the memory to the pointer. Always useNULL
for initialization.这篇关于初始化字符串(字符*)malloc的(0)和NULL之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!