[问题] 请问free分配空间的概念

楼主: liptonbin (我还存在耶)   2023-04-21 11:02:55
请教一下两个问题,如下
为什么path分配空间后,最后面写kfree(path)会导致crash,这样写法是错的吗?
另外code写free_token = token,然后最后kfree(free_token),为什么要多写一个指标去free?
谢谢
int test(struct device *dev, const char *p_i8_buf, size_t count)
{
int i32_ret = 0;
char *temp_buf, *token, *path;
char *free_temp_buf, *free_token;
unsigned long fun = 0;
const char *delim = " ,";
temp_buf = kzalloc(RAYDIUM_FW_BIN_PATH_LENGTH + 1, GFP_KERNEL);
if (temp_buf == NULL)
{
return -ENOMEM;
}
token = kzalloc(RAYDIUM_FW_BIN_PATH_LENGTH + 1, GFP_KERNEL);
if (token == NULL) {
kfree(temp_buf);
return -ENOMEM;
}
path = kzalloc(RAYDIUM_FW_BIN_PATH_LENGTH + 1, GFP_KERNEL);
if (path == NULL) {
kfree(temp_buf);
kfree(token);
return -ENOMEM;
}
free_token = token;
free_temp_buf = temp_buf;
strlcpy(temp_buf, p_i8_buf, count);
token = strsep(&temp_buf, delim);
if(token == NULL)
{
kfree(free_token);
kfree(free_temp_buf);
kfree(path);
return -EINVAL;
}
i32_ret = kstrtoul(token, 16, &fun);
if (i32_ret < 0) {
kfree(free_token);
kfree(free_temp_buf);
kfree(path);
return i32_ret;
}
path = strsep(&temp_buf, delim);//log path
parse(dev, fun, path);
kfree(free_token);
kfree(free_temp_buf);
//kfree(path); //will not crash <
作者: Schottky (顺风相送)   2023-04-21 13:24:00
问题出在 strsep 那一行,你 kfree() 的 path 不是当初kzalloc() 出来的位址
作者: gusion   2023-04-21 13:25:00
你的path在strsep那行被更新了,变成指到temp_buf里面的某个位置,不是原本kzalloc出来的那块,所以最后kfree(path)
作者: Schottky (顺风相送)   2023-04-21 13:25:00
还有 code 麻烦缩排一下,我还要用 indent 缩排过才看得
作者: gusion   2023-04-21 13:25:00
才会出错,另外没有kfree(path),原本allocate的memory就没人free,也会memory leak
作者: Schottky (顺风相送)   2023-04-21 13:25:00
懂你在写什么
作者: gusion   2023-04-21 13:28:00
另外,error handling我是习惯在尾巴加上label,用goto
作者: lycantrope (阿宽)   2023-04-21 17:48:00
2-(2)应该是拿枪射自己脚吧ww

Links booklink

Contact Us: admin [ a t ] ucptt.com