Home > Software design >  Seg fault after failing to loop multiple times in C
Seg fault after failing to loop multiple times in C

Time:03-22

I am doing an exercise where I create an array and populate the elements with integers. I first input the length of the array to malloc for the size. Then, I scan the elements of each point in the array in a for loop.

Here is the code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int scaning(int ** array){
    int size;
    scanf("%d", &size);
    *array = malloc(sizeof(int)*size);
    //printf("%d\n", size);
    for (int i=0; i<=size; i  ){
        int num;
        scanf("%d", &num);
        *array[i] = num;
    }

    return size;
}


int main(){
    
    int * array;
    int zero;
    zero = scaning(&array);
    //printf("%d\n", zero);
    printf("LOOPS\n");
    for (int i=0; i<= zero; i  ){
        printf("%d\n", array[i]);
    }
    return 0;
}

After I input the elements to populate the array twice I get a seg fault. I usually put in size for the array of 5, get to input 2 numbers and then it crashes. Not sure where I went wrong. Any ideas?

CodePudding user response:

The for loops in your program like this

for (int i=0; i<=size; i  ){

have the invalid condition i <= size. The valid range of indices is [0, size).

You need to use the condition i < size.

Another problem is related to the operator precedence.

Instead of

*array[i] = num;

that is equivalent to

*( array[i] ) = num;

you need to write

( *array )[i] = num;

or at least

array[0][i] = num;

The function can be defined the following way

size_t scaning( int **array )
{
    *array = NULL;

    size_t size = 0;
    scanf( "%zu", &size );

    if ( size != 0 ) *array = malloc( sizeof( int ) * size );

    if ( *array != NULL )
    {
        for ( size_t i = 0; i < size; i   )
        {
            int num = 0;
            scanf( "%d", &num );
            ( *array )[i] = num;
        }
    }
    else
    {
        size = 0;
    }

    return size;
}

Correspondingly the variable zero (why is it named "zero"?) also must have the type size_t.

Pay attention to that you should free the allocated array in main like

free( array );

CodePudding user response:

Since size is the number of integers in your array, you don't want to loop until i<=size. You want to loop until i < size only. Remember that the first item in your array has index zero, so the index of the last item is size minus one. If you loop until and including size as index, that will cause a seg fault.

  • Related