arrayscfor-loopfunction-definitionstack-smash

C code showing the error : *** stack smashing detected ***: <unknown> terminated Aborted (core dumped)


I have a program in C that split an array into two sub_arrays , it's perfectly giving results for even & odd array.length , but i have this error :

*** stack smashing detected ***: <unknown> terminated
Aborted (core dumped) 

And this is the C code :

#include <stdio.h>

#define N 7

int arr[N] = {1, 2, 3, 4, 5, 6, 7};

void print(int *array, int start , int finish)
{
    for(int i = start ; i < finish ; i++)
    {
        printf("%d ", array[i]);
        if(i == finish - 1)
            printf("\n");
    }
}
void init(int *array, int start, int finish)
{
    for(int i = start ; i < finish ; i++)
        array[i] = arr[i];
}
int main()
{
    int left[N/2];
    int right[N/2];
    init(left,0,N/2);
    init(right,N/2,N);

    print(left,0,N/2);
    print(right,N/2,N);

    return 0;
}

Solution

  • You declared an array of 3 elements

    #define N 7
    
    //...
    
    int right[N/2];
    

    But you are trying to access elements beyond the array within the function init

    void init(int *array, int start, int finish)
    {
        for(int i = start ; i < finish ; i++)
            array[i] = arr[i];
    }
    

    due to this call

    init(right,N/2,N);
    

    That is the valid range of indices for the array right is [0, N / 2 ) but within the function you are using indices in the range [N /2, N ).

    The same problem exists with the call of the function print

    print(right,N/2,N);
    

    The array right must be declared like

    int right[N - N / 2];
    

    And for example the function init should be defined like

    void init( int *a1, size_t n, const int *a2 )
    {
        for( size_t i = 0 ; i < n ; i++)
            a1[i] = *a2++;
    }
    

    and called like

    init( right, N - N / 2, arr + N / 2 );
    

    In turn the function print can be defined like

    void print( const int *a, size_t n )
    {
        for( size_t i = 0 ; i < n ; i++)
        {
            printf("%d ", a[i]);
        }
    
        putchar( '\n' );
    }
    

    and called like

    print( right, N - N / 2 );
    

    For the array left the function calls will look like

    init( left, N / 2, arr );
    

    and

    print( left, N / 2 );