簡體   English   中英

使用鏈表的分段故障C

[英]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等於04但不超過此值,也沒有阻止它增大的任何限制。

考慮將您的while條件更改為i < 5或類似的條件。 我無法確定您的目標是什么while ( R != NULL )但是R在整個循環中都不會改變,因此條件一旦變為真就不會變為假,反之亦然。

編輯2:

while條件是tail != NULL時類似,僅當malloc分配內存失敗時,該值才為0 在您用完太多內存以致malloc開始失敗之前, i很可能會超過4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM