【发布时间】:2023-03-28 17:29:01
【问题描述】:
我必须在大学班完成一场比赛。这是跳棋游戏。
除了一件事之外,所有作品都按照我老师的指示进行了描述。我需要将历史记录保存在动态内存中(每次移动在 char 数组中都有 5 个字符,所以我使用 malloc 启动“historial”,然后使用大小为 5 + 1 的 calloc。还有“nuevhistorial”临时保存一个只移动,然后将其添加到“历史”中,在接下来的移动中重复使用“新历史”。
我有一个 char *historial,然后我调用 GuardarHistorial 函数。
GuardarHistorial(numjugadas, historial, nuevhistorial);
(numerojugadas 是完成的总步数)
我尝试使用 calloc 或 realloc。
我使用 calloc 增加的代码:
void GuardarHistorial (int *numjugadas, char *historial, char *nuevohistorial) {
int i, j;
char *temp;
temp = (char *) calloc ((HIST*(*numjugadas) + 1), sizeof(char));
if (temp == NULL) {
printf("No se ha podido reservar memoria.");
exit(1);
}
for (i=0; i<HIST*(*numjugadas-1); i++) {
temp[i] = historial[i];
}
for (j=0; i < (*numjugadas) * HIST; i++, j++) {
temp[i] = nuevohistorial[j];
}
historial = temp;
}
我第一次调用函数时,它保存到历史记录,但“历史记录”没有回到它被声明的函数,为什么?它是一个指针……
如果我使用 realloc 的代码是:
void GuardarHistorial (int *numjugadas, char *historial, char *nuevohistorial) {
temp = (char *) realloc (historial, (HIST*(*numjugadas) + 1) * sizeof(char));
if (temp == NULL) {
printf("No se ha podido reservar memoria");
free(historial);
exit(1);
}
historial = temp;
i=(*numjugadas-1) * HIST;
for (j=0; i < (*numjugadas) * HIST; i++, j++) {
historial[i] = nuevohistorial[j];
}
}
在第二个示例中,它似乎可以工作,如果我使用终端或 Netbeans 打开它,则不会显示任何错误。但是用 Valgrind 测试它,在第二步,它完成了程序,在不同的内存地址有很多错误。
我该如何解决?
谢谢!
【问题讨论】:
-
使函数 char *GuardarHistorial 并返回 temp。
-
有人请为此找到一个规范的副本,这是一个非常常见的问题。我试过但失败了……
标签: c pointers dynamic memory-leaks dynamic-memory-allocation