我的以下代码在使用 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);
}
最佳答案
这个:
IFs[ifCount - 1] = (char*) realloc(IFs[ifCount - 1], sizeof(char) * strlen(message));
正在向realloc()
传递一个未初始化的指针,这是错误的原因。
另外:
- 请记住,字符串需要终止空间,上面分配的
strlen(message)
字符太少了 1 个。这将导致strcpy()
在复制时发生缓冲区溢出。 - 请记住,与所有分配堆内存的函数一样,
realloc()
可能会失败。asprintf()
也是如此。 - Don't cast the return value of
realloc()
in C . - 避免
sizeof (char)
,因为它始终为 1,因此对代码增加的值(value)非常小。
关于c - asprintf 为 realloc 覆盖内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13346334/