Home > Net >  Segmentation fault when creating and insert function
Segmentation fault when creating and insert function

Time:12-03

New to C here, I am creating an insert function that will insert any value to an array provided I give the position of the array.

For example, here is what I have tried:

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

int insert(int A[], int N, int P, int KEY){
    int i = N - 1;

    while(i >= P){
        A[i 1] = A[i];
        i  = 1;
    }
    A[P] = KEY;
    N = N 1;
    return *A;
}

int main(void){
    int arr[5] = { 1, 2, 3, 4, 5 };
    size_t n = sizeof(arr)/sizeof(arr[0]);
    int p = 3;
    int K = 2;
    int result;
    result = insert(arr, n, p, K);
    printf("Insert values: %d", result);
    return 0;
}

However, I get the following error:

zsh: segmentation fault ./insert

CodePudding user response:

Accessing out of bounds memory:

The statement is the while loop.

A[i   1] = A[i];

is incorrect. Arrays indices start at 0 in C. Your array consists of 5 elements. The 5th int is the element [4]. You declared i to be (N - 1), which is correct, but then A[i 1] becomes A[5] which is out of bounds, and results in undefined behaviour.

The memory not allocated should not be read.

As an aside, you can use:

i  ; 
N  ; 

as shorthand for:

i = i   1;
N = N   1;

CodePudding user response:

Maybe you are not aware of what is segmentation fault and when does it occur. Lets start with the segmentation fault.

Segmentation fault: A segmentation fault occurs when your program attempts to access an area of memory that it is not allowed to access. In other words, when your program tries to access memory that is beyond the limits that the operating system allocated for your program.

Segmentation faults are mostly caused by pointers that are −

  • Used to being properly initialized.
  • Used after the memory they point to has been reallocated or freed.
  • Used in an indexed array where the index is outside of the array bounds.

Now back to your problem, here you have used i = N - 1 which is 4. Then in the while loop, you are trying to access A[i 1] or A[5] which is outside of the array bounds. Thus you are getting segmentation faults.

  •  Tags:  
  • c
  • Related