【问题标题】:asprintf overwriting memory for reallocasprintf 为 realloc 覆盖内存
【发布时间】:2012-11-01 00:45:11
【问题描述】:

我的以下代码在同时使用asprintfrealloc 时不起作用。

我得到的错误是:

*** glibc detected *** a.out: realloc(): invalid old size: 0x006f1430 ***

根据我的研究,当我使用asprintf 时,它会覆盖realloc 使用的一些内存。这对我来说没有意义,因为asprintf 应该是安全的并且使用适当的字符串长度动态分配。不使用asprintf 会导致程序运行良好,但我的项目需要asprintf 的功能。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
  int ifCount = 1;
  int stringCount = 1;
  char** IFs = NULL;

  //Broken code
  char* message;
  asprintf(&message, "Hello: %d", stringCount);

  //Working code, but not the alternative I want to take
  //char* message = "Hello";

  IFs = (char**) realloc(IFs, sizeof(char*) * ifCount);
  IFs[ifCount - 1] = (char*) realloc(IFs[ifCount - 1], sizeof(char) * strlen(message));
  strcpy(IFs[ifCount - 1], message);

  printf("Message: %s\n", message);
  printf("Copy: %s\n", IFs[ifCount - 1]);
  free(message);
}

【问题讨论】:

  • 当您的问题已在此处解决时,请勿更改帖子名称以在您的问题中包含 (answered)。只需单击解决您问题的答案的复选标记

标签: c printf realloc


【解决方案1】:

这个:

IFs[ifCount - 1] = (char*) realloc(IFs[ifCount - 1], sizeof(char) * strlen(message));

正在将未初始化的指针传递给realloc(),这是错误的原因。

还有:

  1. 记住字符串需要终止空间,上面是分配strlen(message) 字符,1 太少了。这将导致strcpy() 在复制时发生缓冲区溢出。
  2. 请记住,realloc() 与所有分配堆内存的函数一样,可能会失败。 asprintf() 也是如此。
  3. Don't cast the return value of realloc() in C
  4. 避免使用sizeof (char),因为它始终为 1,它为代码增加的价值很少。

【讨论】:

    【解决方案2】:

    不要将reallocNULL 或未初始化的第一个参数一起使用,而是使用malloc 开头。

    如果realloc 调用在IFs[ifCount - 1] = (char*) realloc(...) 调用中是必要的,那么在上一行中,使用calloc 代替 - 这至少会将分配的内存清零,以便realloc 被赋予正确的@987654328 @指针。

    【讨论】:

    • 不,使用calloc(),初始化为全零位,对指针无效。对于NULL 指针,不能保证所有位为零是正确的内存模式。
    • 感谢您的澄清 - 非常感谢。
    猜你喜欢
    • 2011-04-20
    • 1970-01-01
    • 2011-06-08
    • 2015-08-01
    • 1970-01-01
    • 2019-02-21
    • 2011-05-31
    • 1970-01-01
    相关资源
    最近更新 更多