我有一個小程序來動態分配指針數組,因此用戶可以根據需要隨時輸入一個字符數組。我用靈活的指針數組創建了一個結構體。問題是當我試圖從malloc
呼叫free(arrayPtr)
和free(arrayPtr -> str[i])
。它給我錯誤雙免費或腐敗(faststop)。但是當我把它們拿出來的時候。該程序運行良好,但我仍然不明白爲什麼。現場發生了什麼?在這種情況下,我不應該使用free()
嗎?在malloc()調用後雙重釋放或腐敗(faststop)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
/* Get num */
char *getNum()
{
char *_new, *num, c;
int i;
num = malloc(sizeof(char));
for (i = 0; (c = getchar()) != EOF && c != '\n'; i++)
{
_new = realloc(num, i + 2);
num = _new;
num[i] = c;
}
if (c == '\n')
num[i] = '\0';
num[i] = '\0';
return num;
}
struct strHolder {
int size;
char *str[];
};
// Main
int main()
{
char *longNum;
unsigned i = 0;
struct strHolder *arrayPtr = malloc(sizeof (struct strHolder));
for (i = 0; i < 6; i++)
arrayPtr -> str[i] = malloc(sizeof (arrayPtr -> str[i]));
i = 0;
while (i < 6) {
printf("Enter %u number: ", i + 1);
longNum = getNum();
arrayPtr -> str[i++] = longNum;
}
for (i = 0; i < 6; i++)
printf("\nnum is >> %s\n", arrayPtr -> str[i]);
for (i = 0; i < 6; i++)
free(arrayPtr -> str[i]);
free(longNum);
free(arrayPtr);
return 0;
}
那麼我需要從結構中釋放內存嗎?因爲我也爲它調用malloc()。或者從結構的元素釋放內存是否足夠好? –