[英]Segmentation Fault C in use of linked list
我寫了一段返回細分錯誤的代碼。 代碼很長,但我將其基本部分編寫如下。 請注意,已定義了主函數內部所有已定義函數的變量,並且我測試了不在函數_1內的代碼。 這就是為什么我認為問題與聲明有關
typedef struct node_type
{
int data;
struct node_type *next;
} node;
typedef node *list;
void Function_1(list R, int *Matrix, int Length, int A);
int main()
{
int S = 5;
int A = 1;
int Mat1[5];
//int *Mat = malloc(S*sizeof(int));
int *Mat = &Mat1[0];
printf("Enter the Matrix with length of 10:\n");
for (int i = 0; i < S; i++)
{
scanf("%i", &(*(Mat+i)));
}
list head;
head = (list)malloc(sizeof(node));
head->next = NULL;
for (int i = 0; i < S; i++)
{
printf("%d\t", *(Mat+i));
}
//printf("\nEnter the Array = \n");
//scanf("\n%d", &A);
printf("\nA = %i", A);
Function_1(head, Mat, S, A);
while (head != NULL)
{
printf("%d\t", head->data);
head = head->next;
}
return 0;
}
void Function_1(list R, int *Matrix, int Length, int A)
{
printf("11111");
list tail;
tail = R;
int Counter = 0;
int i = 0;
while (tail != NULL)
{
if (*(Matrix+i) == A)
{
Counter++;
tail->next = (list)malloc(sizeof(node));
tail->next->data = i;
tail->next->next = NULL;
tail = tail->next;
}
i++;
}
R->data = Counter;
printf("%d", Counter);
}
謝謝
有了您提供的代碼,我可以說由於缺少<stdlib.h>
或<malloc.h>
包含而導致出現分段錯誤或訪問沖突,從而導致假定malloc
,然后將head
分配給超出您的預期的東西。
我不知道,這也可能是由於您代碼中的隨機點所致。
根據最新的編輯,在函數Function_1
內的循環中,您嘗試訪問Matrix + i
的存儲內容,而i
沒有限制。 可以訪問i
,因為i
等於0
到4
但不超過此值,也沒有阻止它增大的任何限制。
考慮將您的while
條件更改為i < 5
或類似的條件。 我無法確定您的目標是什么while ( R != NULL )
但是R
在整個循環中都不會改變,因此條件一旦變為真就不會變為假,反之亦然。
當while
條件是tail != NULL
時類似,僅當malloc
分配內存失敗時,該值才為0
。 在您用完太多內存以致malloc
開始失敗之前, i
很可能會超過4
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.