小编use*_*386的帖子

asprintf覆盖realloc的内存

我有以下代码,使用asprintf和时都不起作用realloc.

我得到的错误是:

*** glibc detected *** a.out: realloc(): invalid old size: 0x006f1430 ***
Run Code Online (Sandbox Code Playgroud)

基于我所研究的内容,当我使用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 - …
Run Code Online (Sandbox Code Playgroud)

c printf realloc

2
推荐指数
1
解决办法
584
查看次数

标签 统计

c ×1

printf ×1

realloc ×1