Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

c - need help to find segmentation fault error

can someone help me to find what cause segmentation fault in my program, I used the gdb but I cannot find which line that cause the error.

    Array* Merge(Array *arr1, Array *arr2)
{
    int i,j,k;
    i=j=k=0;
    Array *arr3 = (Array*)malloc(sizeof(Array));
    arr3->size = arr1->size + arr2->size;
    arr3->length = arr1->length + arr2->length;
    while(i<arr1->length && j<arr2->length)
    {
        if(arr1->A[i] < arr2->A[j])
            arr3->A[k++]=arr1->A[i++];
        else
            arr3->A[k++]=arr2->A[j++];
    }
    for(;i<arr1->length;i++)
        arr3->A[k++]=arr1->A[i];
    for(;j<arr2->length;j++)
        arr3->A[k++]=arr2->A[j];
    return arr3;
}



 #include <stdio.h>
#include <stdlib.h>
#include "array1.h"
int main()
{
        Array arr,arr1,*arr2;
        arr.size=10;
        arr.length=5;
        arr1.size=10;
        arr1.length=5;
        arr.A=(int*)malloc(arr.size*sizeof(int));
    arr1.A=(int*)malloc(arr.size*sizeof(int));
        printf("
 enter elements of arr
");
        for (int i=0;i<arr.length;i++)
            scanf("%d",&arr.A[i]);
    /**********************************************/
        printf("
 enter elements of arr1
");
        for (int i=0;i<arr1.length;i++)
            scanf("%d",&arr1.A[i]);
        arr2=Merge(&arr, &arr1);
        display(*arr2);
    return 0;
}

here is the result of the gdb enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In Merge you don't allocate any space for arr3's data (probably a member called A looking at the other code)

It would help to see the rest of the code (especially the declaration of Array) but I suspect arr3->A is an uninitialised pointer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...