c - asprintf 为 realloc 覆盖内存

标签 c printf realloc

我的以下代码在使用 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);
}

最佳答案

这个:

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,因此对代码增加的值(value)非常小。

关于c - asprintf 为 realloc 覆盖内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13346334/

相关文章:

正确的二维数组内存分配/解除分配?

c - 为什么编译器要向已经 4 字节对齐的结构添加填充?

C 语言 - 将解决方案存储到输出文件中 - 防止下一行之前出现空格字符

c - 检测到 glibc,realloc() : invalid next size:X

对 sprintf 格式 '-Flag 的跨平台支持

c - 使用指数表示法时 printf 中的奇怪符号

C语言中与realloc的混淆

c++ - 将对象初始化为全零

c - 数字中特定位数的个数

c - 以下哪个函数在 C 中更容易测试?