gpt4 book ai didi

c - 释放 malloc 指针时出错

转载 作者:行者123 更新时间:2023-11-30 15:12:24 24 4
gpt4 key购买 nike

在以下代码中释放 malloc 字符串时遇到错误:

long authenticate(char* user, long* uid, long* gid){
FILE* fp = fopen("/etc/passwd", "r");
char * line = NULL;
size_t len = 0;
long lineSize;
char* uname;

if (fp == NULL)
exit(EXIT_FAILURE);

while ((lineSize = getline(&line, &len, fp)) != -1) {

uname = (char*)malloc(lineSize*sizeof(char));
getInfo(line, lineSize, &uname, &uid, &gid);

if(strcmp(uname, user) == 0) { // Strings are equal
printf("we've found a user!\n");
printf("uname: %s uid: %ld gid: %ld\n", uname, *uid, *gid);
free(uname);
exit(1);
}

free(uname);
}
}

每当我找到有效的用户名时,释放uname,然后退出,什么也没有发生。但是,当我在循环末尾尝试释放 uname 时找不到有效的 uname (if 语句未评估)时,我会得到以下信息错误:

malloc: *** error for object 0x10d20ef2c: pointer being freed was not allocated

我不明白为什么 free() 没有注册 uname 之前已进行 malloc。考虑到该错误的性质,我相信问题是我不了解malloc/free

最佳答案

问题很可能是 getInfo()修改位置 uname指向,之后 free() 无法识别它.

关于c - 释放 malloc 指针时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35099602/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com