[問題] 請問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