【发布时间】:2021-03-28 14:17:39
【问题描述】:
我应该在不使用库的情况下实现 strcpy 函数。我已经为此编写了代码,但似乎有一个错误(可能是内存泄漏,但我不确定)
但是,如果你们中的任何人都可以提供提示,是否是内存泄漏以及如何修复它,这将非常有帮助。
头文件:
实现文件:
#include "string.h"
#include <string.h>
#include <stdlib.h>
void copy (string *s1, string s2) {
free((*s1));
char *temp = malloc(strlen(s2 ->s) + 1);
if(s2 -> s != NULL) {
int i = 0;
while(s2 -> s[i] != '\0') {
temp[i] = s2 -> s[i];
i++;
}
temp[i] = '\0';
(*s1) -> s = temp;
free(temp);
}
}
据我所知,设置字符串效果很好,复制功能似乎有问题。
【问题讨论】:
-
@MatheusRossiSaciotto 字符串是可怕的 typedefd 指针。
-
如果你免费
free(temp);(*s1) -> s也发布了 -
Set中的(*s1) -> s = s;无效,您使用的是引用,对象依赖于 char 数组 -
temp和(*s1) -> s指向同一个内存,如果你释放这块内存,你就会毁掉这两个内存。当你使用 free 时,你正在释放内存,指针只是变量,就像一个 int。 -
你有一个指针副本,正在删除内存。