最近開始練習鏈表。我知道基本的演算法和概念,以及實作 LL 來存盤用戶輸入的一堆字串的想法。
但顯然我不斷得到Segmentation fault.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _node{
char *s;
struct _node *next;
}
node;
int main()
{
node *head = NULL;
int a = 0;
char ch;
char *str = malloc(10);
do
{
printf("\nDude %i:", a);
fgets(str, 10, stdin);
node *n = malloc(sizeof(node));
if(n == NULL)
{
printf("\ninsufficient memory");
return 1;
}
if(a == 0)
{
strcpy(n->s, str);
n->next = NULL;
head = n;
}
else
{
strcpy(n->s, str);
n->next = head;
head = n;
}
a ;
printf("\n continue?(y/n): ");
scanf("\n%c", &ch);
}while(ch == 'y');
for(node *temp = head; temp != NULL; temp = temp -> next)
{
printf("\n%s", temp->s);
}
return 0;
}
我確實明白我的邏輯/代碼在某處存在缺陷,因為我正在接觸我不應該接觸的記憶體,但似乎無法指出哪里,因為這是我第一次處理鏈表。
uj5u.com熱心網友回復:
當您為malloc'ing 空間時struct,您只是為結構中指向字串的指標分配空間_node。您需要分配您存盤的字串一些記憶體和指標指向s它,你做之前strcpy。IE
n->s = malloc(sizeof(char)*100);
請記住,您還需要有一個策略來取消分配此記憶體。
正如其他人所暗示的那樣,通過使用gdb. 請記住,使用-g標志進行編譯以獲得有用的除錯資訊很有用。
uj5u.com熱心網友回復:
你趕上一個'分段故障”的原因是因為你沒有為分配記憶體s結構的變數node拷貝實際字串之前:strcpy(n->s, str)。因此,為s以下分配記憶體:
n->s = (char *) malloc(10 * sizeof(char));
uj5u.com熱心網友回復:
請注意,您不能將任何內容寫入未分配的空間,因此您需要malloc在每個節點中呼叫該字串。如果字串長度是固定的,那么你可以在定義中指定長度struct node來避免這個malloc問題。
此外,建議始終free將不再參考的物件。
經過一些修改,以下代碼可能會有所幫助:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 10
typedef struct node {
char str[LEN];
struct node *next;
} Node;
int main() {
Node *head = NULL;
int n = 0;
char c = 'y';
while (c == 'y') {
Node *node = malloc(sizeof(Node));
printf("Node #%d: ", n);
scanf(" ");
/* Store the string directly into the node. */
fgets(node->str, 10, stdin);
/* Remove the newline character. */
node->str[strcspn(node->str, "\n")] = 0;
node->next = head;
head = node;
n;
printf("Continue? (y/N): ");
scanf("%c", &c);
};
Node *curr = head;
while (curr != NULL) {
printf("%s\n", curr->str);
Node *temp = curr;
curr = curr->next;
/* Remember to free the memory. */
free(temp);
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/385067.html
