Home > OS >  Segmentation fault (core dumped) error while deletion of an element in an array
Segmentation fault (core dumped) error while deletion of an element in an array

Time:12-10

I wrote a basic code to create an array dynamically:

void makeArray(struct Array * a)
{
    int capacity, need;
    printf("Enter the capacity of the array you want: ");
    scanf("%d", &capacity);
    printf("Enter the capacity you are going to use: ");
    scanf("%d", &need);
    a -> used_size = need;
    a -> total_size = capacity;
    a -> ptr = (int*)malloc (capacity * sizeof(int));
}

I created a function to delete elements from the array:

void indDeletion(struct Array * a)
{
    int index;
    printf("Enter the position you would like to delete the number in: ");
    for(int i = index; a -> used_size - 1; i  )
    {
        a -> ptr[i] = a -> ptr[i 1];
    }
    a -> used_size -= 1;

}

The code works fine when I insert the elements but the when i call the deletion function it shows Segmentation fault (core dumped).

Here is what the output looks like:

Enter the capacity of the array you want: 100
Enter the capacity you are going to use: 4
Enter element 0: 1
Enter element 1: 2
Enter element 2: 3
Enter element 3: 4
Element 0: 1
Element 1: 2
Element 2: 3
Element 3: 4
Enter the position you would like to insert the number in: 3
Enter the number: 123
Insertion was successful
Element 0: 1
Element 1: 2
Element 2: 3
Element 3: 123
Element 4: 4
Segmentation fault (core dumped)

CodePudding user response:

You forgot to scanf for index in the deletion function.

Also, this code does not look right:

    for(int i = index; a -> used_size - 1; i  )
    {
        a -> ptr[i] = a -> ptr[i 1];
    }

The condition a -> used_size -1 will never change because you never modify a -> used_size in the loop. So either the loop will never run, or it will run forever.

Another point - when moving the elements you can use a bulk function like memmove() instead of writing a loop yourself and risking making a mistake. This is explained in this thread. You could replace the loop with something like:

memmove(&(a->ptr)[i], &(a->ptr)[i 1], (a->used_size - 1 - index)*sizeof(int));
  • Related