【问题标题】:Why am I getting error when calling realloc on a char[]?为什么在 char[] 上调用 realloc 时会出错?
【发布时间】:2014-02-26 13:09:13
【问题描述】:

我有 char[] 这样的

char string[] = "Hello world !!!";

当我尝试重新分配它的内存时,我遇到了错误

realloc(string, 50); // error here

【问题讨论】:

    标签: c undefined-behavior realloc


    【解决方案1】:

    你只能realloc 事情你malloc/calloc/realloc'ed。 char 数组不是这些东西,所以在这种情况下出现错误是正常的。

    【讨论】:

      【解决方案2】:

      除非 ptr 为 NULL,否则它一定是由先前对 malloc()、calloc() 或 realloc() 的调用返回的

      您违反了标准,因此您将获得未定义行为的奖励。

      【讨论】:

        【解决方案3】:
        realloc(string, 50);
        

        realloc() 的参数,即string 应通过malloc()calloc()realloc() 获得,如果不为空

        【讨论】:

          猜你喜欢
          • 2022-01-17
          • 2015-01-27
          • 2022-07-22
          • 1970-01-01
          • 2010-09-05
          • 1970-01-01
          • 2021-07-26
          • 2015-08-29
          • 1970-01-01
          相关资源
          最近更新 更多