我的程式運行時沒有錯誤,但是當我想釋放 2D 字符陣列(如 arguments[0])時,它給了我:free(): invalid pointer, fish: Job 1, './a.out' 由信號 SIGABRT 終止(中止)
/**
* @brief Parses the input into arguments
*
* EXP:
* "head -n 5 foo.txt"
* arguments[0] = "head"
* arguments[1] = "-n"
* arguments[2] = "5"
* arguments[3] = "foo.txt"
* arguments[4] = NULL
*
* @param input
* @return char**
*/
char** getArguments(char* input, int numOfArgs) {
char copy_arguments[BUFSIZ]; /* To parse input */
strcpy(copy_arguments, input);
char** arguments = calloc(numOfArgs 1, sizeof(char*));
if (arguments == NULL) {
return NULL;
}
/*allocate memory for arguments depending their length*/
char* argument = NULL;
for (int i = 0; i < numOfArgs; i ) {
if (i == 0) {
argument = strtok(copy_arguments, " ");
} else {
argument = strtok(NULL, " ");
}
int size_of_arg = strlen(argument);
arguments[i] = calloc((size_of_arg 1), sizeof(char));
strcpy(arguments[i], argument);
}
arguments[numOfArgs 1] = NULL;
return arguments;
}
int main() {
char **output = getArguments("hello world -n vim", 4);
free(output[0]);
}
uj5u.com熱心網友回復:
該函式呼叫未定義的行為。有分配的numOfArgs 1指標
char** arguments = calloc(numOfArgs 1, sizeof(char*));
所以索引的有效范圍是[0, numOfArgs]。
因此在這個宣告中
arguments[numOfArgs 1] = NULL;
可以訪問分配的陣列之外的記憶體。
相反,你必須寫
arguments[numOfArgs] = NULL;
一般來說,您應該檢查回傳的指標是否不等于NULL例如
if ( output ) free(output[0]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/490692.html
