【发布时间】:2019-10-25 08:31:41
【问题描述】:
我希望能够将一个字符串传递给一个函数,该函数采用构成字符串的字符数组并将其更改为提供的另一个字符串。问题是我收到一条错误消息,告诉我正在重新分配的指针(使用 realloc)尚未分配(使用 malloc)。
我确保函数中使用的指针与主程序中使用的指针相同,如指针打印语句所示。我试过不传入字符串 char 数组地址,而只是传入本身。这些都没有奏效。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void change(char **old_string, char *new_string);
int main(int argc, char *argv[]) {
if (argc == 2) {
char *string;
string = malloc((strlen(argv[1]) + 1) * sizeof(char)); // + 1 for \0
string = argv[1];
printf("Pointer outside Function: %p\n", string);
printf("String Before: %s\n", string);
change(&string, "New String");
printf("String After: %s\n", string);
} else {
printf("Please enter a string to have changed.\n");
}
return 0;
}
void change(char **old_string, char *new_string) {
printf("Pointer in Function: %p\n", *old_string);
*old_string = realloc(*old_string, (strlen(new_string) + 1) * sizeof(char)); // + 1 for \0
strcpy(*old_string, new_string);
}
运行时的当前结果是:
函数外部指针:0x7ffeed590c88 字符串之前:测试 函数中的指针:0x7ffeed590c88 a.out(20309,0x111496d40) malloc: * 对象 0x7ffeed590c88 的错误:未分配重新分配的指针 a.out(20309,0x111496d40) malloc: * 在 malloc_error_break 中设置断点进行调试 中止陷阱:6
应该发生什么:
应该为函数提供两个字符串。第一个参数是指向字符的指针,第二个是字符串文字。提供的字符指针应该可以在主程序中使用。
【问题讨论】:
-
这是您的问题
string = argv[1];您正在将指针分配给未mallocated的东西 -
您是否确保指向您尝试重新分配的内存的指针与您分配内存时返回的指针相同?
-
请注意,在 C 中,
sizeof(char)保证等于 1。 -
如何调试:呵呵 realloc 崩溃。我收到一条消息说数据不是由 malloc 分配的。所以传递给 realloc 的指针一定是坏的。看看函数调用,看起来还可以。 malloc会不会有问题?检查 malloc 代码。当您查看代码中相邻的两行时,您应该会在附近的某个地方听到花里胡哨的声音,第一行
string = malloc ...和下一行string = something else。