初始化字符串(字符*)malloc的(0)和NULL之间的区别 [英] Difference between initializing a string with (char *)malloc(0) and NULL

查看:154
本文介绍了初始化字符串(字符*)malloc的(0)和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

  • 返回一个指针,它可以传递给免费()

但不管怎么说,取消引用该指针是不允许的。这将导致外结合的内存访问,并导致不确定的行为

这是说,两个重要的事情提了,


  1. 明白为什么不能投 的malloc的返回值()和家人在 C


  2. 请检查返回值的malloc()使用前返回的指针。


因此​​,要回答你的问题,


  

初始化字符串之差(字符*)malloc的(0)和NULL


不要使用的malloc(0)在这种情况下,作为指针空支票的可能的失败,给了错误的IM pression内存指针的的有效的分配。始终使用 NULL 初始化。

Why allocating a 0 size char block works in this case? But if I write char *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, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

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,

  1. Please see why not to cast the return value of malloc() and family in C.

  2. 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 NULL

Do 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 use NULL for initialization.

这篇关于初始化字符串(字符*)malloc的(0)和NULL之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆