Search code examples
cscopefunction-definitionvariable-length-arraystorage-duration

Adding two corresponding array elements and return the resultant array


Facing segmentation fault in the following code . Can anyone help me fix it?

#include<stdio.h>

int* multiply(int *arr1, int *arr2, int m);

int main(void){
    int m = 0;
    
    
    printf("Enter size of array1 and array2 >");
    scanf("%d",&m);

    int arr1[m],  arr2[m];
        printf("First array>");

    for(int i = 0; i < m; ++i){
        scanf("%d", &arr1[i]);
    }
    printf("Second array> ");
    for(int j = 0; j < m; j++)
       scanf("%d", &arr2[j]);

    
    
    int* result = multiply(arr1, arr2, m);

    for(int i = 0; i < m; ++i){
        printf("%d ", result[i]);
    }
    


}

int* multiply(int *arr1, int *arr2, int m){
    int res[m];
    printf("ok");
    for(int i = 0; i < m; ++i){
        res[i] = arr1[i] + arr2[i];
    }
    printf("ok");
    return res;
}

Output should show like

Enter size of array1 and array2 >3

First array>5 1 7

Second array> 2 4 2

The resultant > 7 5 9

My output

Enter size of array1 and array2 >3

First array>5 1 7

Second array> 2 4 2

Segmentation fault


Solution

  • The program has undefined behavior because the function multiply returns a pointer to the local array res that will not be alive after exiting the function. So after exiting the function the returned pointer will be invalid.

    int* multiply(int *arr1, int *arr2, int m){
        int res[m];
        printf("ok");
        for(int i = 0; i < m; ++i){
            res[i] = arr1[i] + arr2[i];
        }
        printf("ok");
        return res;
    }
    

    You need to allocate memory dynamically for the array. Also the parameters that denote arrays should have qualifier const because passed arrays are not changed within the function.

    The function can be declared and defined the following way.

    int * multiply( const int *arr1, const int *arr2, size_t n )
    {
        int *res = NULL;
    
        if ( n != 0 && ( res = malloc( n * sizeof( int ) ) ) != NULL )
        {
            for( size_t i = 0; i < n; ++i )
            {
                res[i] = arr1[i] + arr2[i];
            }
        }
    
        return res;
    }
    

    In main you should write

    int* result = multiply(arr1, arr2, m);
    
    if ( result != NULL )
    {
        for(int i = 0; i < m; ++i){
            printf("%d ", result[i]);
        }
    }
    
    free( result );