typedef struct{
char** strings_cmd;
int size_cmd;
}parseInfo;
……
parseInfo* parse(char* cmd){
char* temp = strdup(cmd);
char* temp_split = strtok(temp," ");
int i = 0;
char** strings = (char**)malloc(sizeof(char*));
if(strings == NULL){
printf("no memory allocated strings parse()\n");
exit(1);
}
while(temp_split != NULL){
strings[i ] = strdup(temp_split);
strings = realloc(strings,i * sizeof(char*));
if(strings == NULL){
printf("no memory allocated strings (while) parse()\n");
exit(1);
}
temp_split = strtok(NULL," ");
}
strings[i] = NULL;
parseInfo* info = (parseInfo*)malloc(sizeof(parseInfo));
if(info == NULL){
printf("no memory allocated info parse()\n");
exit(1);
}
info->strings_cmd = strings;
info->size_cmd = i;
return info;
}
大家好,我得到了錯誤:
realloc():下一個大小無效。
我嘗試做的是輸入一個字串并將其拆分為單詞,例如我輸入=“Hello World”。并將其拆分 = "Hello" , "World"
但是當我傳遞 4 個單詞時,我得到了這個錯誤......
uj5u.com熱心網友回復:
對于初學者來說,函式存在記憶體泄漏,因為在函式的開頭分配了記憶體
parseInfo* parse(char* cmd){
char* temp = strdup(cmd);
//...
那沒有被釋放。
在這個while回圈中
while(temp_split != NULL){
strings[i ] = strdup(temp_split);
strings = realloc(strings,i * sizeof(char*));
if(strings == NULL){
printf("no memory allocated strings (while) parse()\n");
exit(1);
}
temp_split = strtok(NULL," ");
你需要寫
strings = realloc(strings, ( i 1 ) * sizeof(char*));
為該陳述句中使用的終止空指標保留一個元素
strings[i] = NULL;
而且您需要在函式的開頭釋放分配的動態記憶體,例如
free( temp );
}
您正在分配一個指標陣列,其中需要的元素少了一個。
uj5u.com熱心網友回復:
這條線很糟糕:
strings = realloc(strings,i * sizeof(char*));
此行正在將陣列大小調整為i元素。然后,在下一次迭代中,一些值被存盤到i陣列的第 - 個元素(指向 by)strings。該陣列只有i元素 ( 0to i-1),因此這是超出范圍的訪問。
分配足夠的元素來修復:
strings = realloc(strings,(i 1) * sizeof(char*));
另請注意,malloc()家庭的鑄造結果被認為是一種不好的做法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/455475.html
上一篇:如何在這個問題中使用近似演算法?
下一篇:提取exec函式的引數
