分段錯誤我試圖創建一個臨時的'迭代器'結構,它被分配到'列表'的開頭,然後通過檢查iterator->next != NULL
遍歷結構列表。我相信這個問題在iterator = start
行(35 & 70)。分配結構=結構
該應用程序編譯時沒有任何問題,但是當我應用程序出現分段錯誤時(核心轉儲)。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct record
{
int accountno;
char name[25];
char address[80];
struct record* next;
};
int addRecord (struct record **, int, char [], char []);
void printAllRecords(struct record *);
int main(int argc, char *argv[]) {
struct record ** start;
start = NULL;
addRecord(start, 1, "Record Name", "Record Address");
printAllRecords(*start);
return 0;
}
void printAllRecords(struct record * start)
{
struct record * recordIterator;
/* Allocate the required memory and return a pointer to it */
recordIterator = malloc(sizeof(struct record));
/* Start at the beginning */
recordIterator = start;
printf("\n\n%10s %20s %20s\n", "accountno", "Name", "Address");
while (recordIterator != NULL)
{
printf("%10d %20s %20s\n", recordIterator->accountno, recordIterator->name, recordIterator->address);
recordIterator = recordIterator->next;
}
}
int addRecord (struct record ** start, int accountno, char name[], char address[])
{
struct record * newRecord;
/* Allocate the required memory and return a pointer to it */
newRecord = malloc(sizeof(struct record));
/* Assign values to the new record */
newRecord->accountno = accountno;
strcpy(newRecord->name, name);
strcpy(newRecord->address, address);
if (start == NULL)
{
start = &newRecord;
}
else
{
struct record * recordIterator;
/* Allocate the required memory and return a pointer to it */
recordIterator = malloc(sizeof(struct record));
/* Start at the beginning */
recordIterator = *start;
while (recordIterator->next != NULL)
{
recordIterator = recordIterator->next;
}
recordIterator->next = newRecord;
}
return 1;
}
'addRecord'中的'start'是本地副本。函數返回後,這種更改不會被反映出來。 –
爲什麼只是動態分配內存才能立即拋出內存?你的程序泄漏內存......壞 – StoryTeller
沒有理由說明'start'應該是main中的指針指針。將其聲明爲一個普通指針,然後將其地址傳遞給該函數。 – Lundin