Common Scenarios for Segmentation fault (Core dumped) Error3 months ago

Let us now look at the most common scenarios where core dumped error can occur in C programming.

Scenario 1: 
We forget to include & - the address of operator in statements involving scanf function.

The below program will give Segmentation fault (Core dumped) error when executed.

#include <stdio.h>

int main()
{
    int x,y;
    scanf("%d%d",x,y); //It must be &x,&y
    printf("%d", x+y);
    return 0;
}

 

Scenario 2:
We use a char array (String) to accept a string value which is larger than it's length.

The below program will give 
*** stack smashing detected ***:  terminated
Aborted (core dumped) error when executed.

#include <stdio.h>

int main()
{
    char str[3];
    scanf("%s",str); 
    /*
     * Input is abcdefghijklmnopqrstdsjskdhkdhkdhskjdhsjdskjdhskjdhsjdhskjdhskj whose 
     * length is more than size of str which is 3
     */ 
    
    printf("%s",str);
    return 0;
}

 

Scenario 3:
When we traverse beyond the memory allocated for the Array.

The below program will give Segmentation fault (core dumped) error.

#include <stdio.h>

int main()
{
    char str[3];
    str[0] = 's';
    str[1] = 'r';
    str[2] = 'a';
    /*
	Array str size is only 3 but we traverse till 50000.
    */
    for(int index=0; index < 50000; index++){
        printf("%c",str[index]);
    }
    return 0;
}

 

Scenario 4:
When we use %s format specifier for printing a character.

The below program will give Segmentation fault (core dumped) error.

#include<stdio.h>

int main()
{
    char str[101] = "hello";
    printf("%s", str[1]);
}

 

Scenario 5:
When we return an array which is declared in the same function.

The below program will give Segmentation fault (core dumped) error.

#include <stdio.h>

int* fun(){
    int arr[100];
    arr[0] = 1;
    return arr;
}
int main()
{
    int *arr = fun();
    printf("%d", arr[0]);
    return 0;
}