【发布时间】:2012-11-01 00:45:11
【问题描述】:
我的以下代码在同时使用asprintf 和realloc 时不起作用。
我得到的错误是:
*** 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)。只需单击解决您问题的答案的复选标记