Scanf ошибка сегментирования

noob question here:
I’m trying to write a simple menu interface, but I keep getting a segmentation fault error and I can’t figure out why.

#include <stdlib.h>
#include <stdio.h>
int flush(); int add(char *name, char *password, char *type); int delete(char *name);
int edit(char *name, char *password, char *type, char *newName, char *newPassword, char            *newType);
int verify(char *name, char *password);



int menu(){
    int input;
    char *name, *password, *type, *newName, *newPassword, *newType;
    printf("MAIN MENU n ============n");
    printf("1. ADDn");
    printf("2. DELETEn");
    printf("3. EDITn");
    printf("4. VERIFYn");
    printf("5. Exitn");
    printf("Selection:");
    scanf("%d", &input);
    flush();
    switch (input){

    case 1:
        printf("%sn", "Enter Name:");
        scanf("%s", name);
        flush();
        printf("%sn", "enter password" );
        scanf("%s", password);
        flush();
        printf("%sn","enter type" );
        scanf("%s",type);
        add(name, password, type);
        menu();
        break;
    case 2:
        printf("Enter Name:" );
        scanf("%s",name);
        flush();
        delete(name);
        menu();
        break;
    case 3:
        printf("Enter Name:n");
        scanf("%s",name);
        flush();
        printf("Enter Passwordn");
        scanf("%s", password);
        flush();            
        printf("enter type:n");
        scanf("%s", type);
        flush();
        printf("enter your new username:n");
        scanf("%s",newName);
        flush();
        printf("enter your new passwordn");
        scanf("%s", newPassword);
        flush();
        printf("enter your new typen");
        scanf("%s",newType);
        flush();
        edit(name, password, type, newName, newPassword, newType);
        menu();
        break;
    case 4:
        printf("Enter Namen");
        scanf("%s",name);
        flush();
        printf("Enter Passwordn");
        scanf("%s",password);
        flush();
        verify(name, password);
        menu();
        break;
    case 5:
        return 0;
    default:
        printf("invalid input, please select from the following:n");
        menu();
}
    return 0;
    }

    int flush(){
     int ch;
     while ((ch = getchar()) != EOF && ch != 'n') ;
     return 0;
    }

I get the segmentation fault after entering two fields, in any menu option

I am trying to scan in an integer to use for my program. However my program gives me segmentation fault during compilation this is the section that is giving me the error:

int main(void)
{
    int totalHeight=0, floorWidth=0, amountOfStories, amountWindowForTop, amountWindowForMiddle, amountWindowForBottom, windowHeight, middleWindowWidth, topWindowWidth, bottomWindowWidth, minimumHeight, minimumWidth;

    char topFloorWindowContent, middleFloorWindowContent, bottomFloorWindowContent, windowBorder, floorBorder;

    int tempMax;

    printf("please enter how many stories your building would like to have: ");
    scanf("%d",&amountOfStories);
    minimumHeight=amountOfStories*6+1;
    while((totalHeight<minimumHeight)||((totalHeight%amountOfStories)!=1))
    {
        printf("please enter the totalHeight (minimum %d): ",minimumHeight);
        scanf("%d",&totalHeight);
    }
    printf("please enter how many window building would have for top floor: ");
    scanf("%d",amountWindowForTop);
    printf("please enter how many window building would have for middle floors: ");

now my program after compile only runs to the scanf on the amoutWindowForTop
after I enter in the value for that it just gives me segmentation fault I have no idea why. Because I am not using pointers so why is it giving me that error?everything seemed in order for me
this is the output

please enter how many stories your building would like to have: 5
please enter the totalHeight (minimum 31): 31
please enter how many window building would have for top floor: 2
Segmentation fault

Segmentation faults in C or C++ is an error that occurs when a program attempts to access a memory location it does not have permission to access. Generally, this error occurs when memory access is violated and is a type of general protection fault. Segfaults are the abbreviation for segmentation faults.

The core dump refers to the recording of the state of the program, i.e. its resources in memory and processor. Trying to access non-existent memory or memory which is being used by other processes also causes the Segmentation Fault which leads to a core dump.

A program has access to specific regions of memory while it is running. First, the stack is used to hold the local variables for each function. Moreover, it might have memory allocated at runtime and saved on the heap (new in C++ and you may also hear it called the “free store“). The only memory that the program is permitted to access is it’s own (the memory previously mentioned). A segmentation fault will result from any access outside of that region. 

Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you“:

  • When a piece of code tries to do a read-and-write operation in a read-only location in memory or freed block of memory, it is known as a segmentation fault.
  • It is an error indicating memory corruption.

Common Segmentation Fault Scenarios

In a Segmentation fault, a program tries to access memory that is not authorized to access, or that does not exist. Some common scenarios that can cause segmentation faults are:

  1. Modifying a string literal
  2. Accessing an address that is freed
  3. Accessing out-of-array index bounds
  4. Improper use of scanf()
  5. Stack Overflow 
  6. Dereferencing uninitialized pointer 

1. Modifying a String Literal

The string literals are stored in the read-only section of the memory. That is why the below program may crash (gives segmentation fault error) because the line *(str+1) = ‘n’ tries to write a read-only memory.

Example:

C

#include <stdio.h>

int main()

{

    char* str;

    str = "GfG";

    *(str + 1) = 'n';

    return 0;

}

C++

#include <iostream>

using namespace std;

int main()

{

    char* str;

    str = "GfG";

    *(str + 1) = 'n';

    return 0;

}

 Output

timeout: the monitored command dumped core

/bin/bash: line 1:    32 Segmentation fault      timeout 15s ./83b16132-8565-4cb1-aedb-4eb593442235 < 83b16132-8565-4cb1-aedb-4eb593442235.in

Refer, to Storage for Strings in C for more details.

2. Accessing an Address That is Freed

Here in the below code, the pointer p is dereferenced after freeing the memory block, which is not allowed by the compiler. Such pointers are called dangling pointers and they produce segment faults or abnormal program termination at runtime.

Example:

C

#include <stdio.h>

#include <stdlib.h>

int main(void)

{

    int* p = (int*)malloc(8);

    *p = 100;

    free(p);

    *p = 110;

    printf("%d", *p);

    return 0;

}

C++

#include <iostream>

using namespace std;

int main(void)

{

    int* p = (int*)malloc(sizeof(int));

    *p = 100;

    free(p);

    *p = 110;

    return 0;

}

Output

Segmentation Fault

3. Accessing out-of-bounds Array Index

In C and C++, accessing an out-of-bounds array index may cause a segmentation fault or other undefined behavior. There is no boundary checking for arrays in C and C++. Although in C++, the use of containers such as with the std::vector::at() method or with an if() statement, can prevent out-of-bound errors.

Example:

C

#include <stdio.h>

int main(void)

{

    int arr[2];

    arr[3] = 10;

    return (0);

}

C++

#include <iostream>

using namespace std;

int main()

{

    int arr[2];

    arr[3] = 10;

    return 0;

}

Output

Segmentation Faults

4. Improper use of scanf()

The scanf() function expects the address of a variable as an input. Here in this program n takes a value of 2 and assumes its address as 1000. If we pass n to scanf(), input fetched from STDIN is placed in invalid memory 2 which should be 1000 instead. This causes memory corruption leading to a Segmentation fault.

Example:

C

#include <stdio.h>

int main()

{

    int n = 2;

    scanf("%d", n);

    return 0;

}

C++

#include <iostream>

using namespace std;

int main()

{

    int n = 2;

    cin >> n;

    return 0;

}

Output

Segementation Fault

5. Stack Overflow

It’s not a pointer-related problem even code may not have a single pointer. It’s because of running out of memory on the stack. It is also a type of memory corruption that may happen due to large array size, a large number of recursive calls, lots of local variables, etc.

Example:

C

#include <stdio.h>

int main()

{

    int arr[2000000000];

    return 0;

}

C++

#include <iostream>

using namespace std;

int main()

{

    int array[2000000000];

    return 0;

}

Output

Segmentation Fault

6. Buffer Overflow

If the data being stored in the buffer is larger than the allocated size of the buffer, a buffer overflow occurs which leads to the segmentation fault. Most of the methods in the C language do not perform bound checking, so buffer overflow happens frequently when we forget to allot the required size to the buffer.

Example:

C

#include <stdio.h>

int main()

{

    char ref[20] = "This is a long string";

    char buf[10];

    sscanf(ref, "%s", buf);

    return 0;

}

C++

#include <iostream>

using namespace std;

int main()

{

    char ref[20] = "This is a long string";

    char buf[10];

    sscanf(ref, "%s", buf);

    return 0;

}

Output

Segmentation Fault

7. Dereferencing an Uninitialized or NULL Pointer

It is a common programming error to dereference an uninitialized pointer (wild pointer), which can result in undefined behavior. When a pointer is used in a context that treats it as a valid pointer and accesses its underlying value, even though it has not been initialized to point to a valid memory location, this error occurs. Data corruption, program errors, or segmentation faults can result from this. Depending on their environment and state when dereferencing, uninitialized pointers may yield different results.

As we know the NULL pointer does not points to any memory location, so dereferencing it will result in a segmentation fault.

Example:

C

#include <stdio.h>

int main()

{

    int* ptr;

    int* nptr = NULL;

    printf("%d %d", *ptr, *nptr);

    return 0;

}

C++

#include <iostream>

using namespace std;

int main()

{

    int* ptr;

    int* nptr = NULL;

    cout << *ptr << " " << *nptr;

    return 0;

}

Output

Segmentation Fault

How to Fix Segmentation Faults?

We can fix segmentation faults by being careful about the causes mentioned:

  • Avoid modifying string literals.
  • Being careful when using pointers as they are one of the most common causes.
  • Considering the buffer and stack size before storing the data to avoid buffer or stack overflow.
  • Checking for bounds before accessing array elements.
  • Use scanf() and printf() carefully to avoid incorrect format specifiers or buffer overflow.

Overall, the cause of the segmentation fault is accessing the memory that does not belong to you in that space. As long as we avoid doing that, we can avoid the segmentation fault. If you cannot find the source of the error even after doing it, it is recommended to use a debugger as it directly leads to the point of error in the program.

Last Updated :
07 May, 2023

Like Article

Save Article

ошибка сегментирования


0

0

начал изучать СИ, столкнулся с ошибкой сегментирования в gcc


char *c;
scanf(«%s»,c); // на этом месте возникает ошибка
printf(«%s»,c);

будете пинать, но в turbo c, такой ошибки невозникает

  • Ссылка

Re: ошибка сегментирования

char *c 
scanf("%s",c) // на этом месте возникает ошибка 
printf("%s",c)

anonymous

(18.09.08 20:48:24 MSD)

  • Показать ответ
  • Ссылка

Re: ошибка сегментирования

ты забыл выделить память.
char* c; //здесь c указывает куда угодно, и scanf пишет куда-угодно, вот и ругается система.

help_us

(18.09.08 20:51:36 MSD)

  • Ссылка

Re: ошибка сегментирования

> но в turbo c, такой ошибки невозникает

Windows сразу выдает BSOD? :D

#define N 10
char* c = (char *)malloc(sizeof(char) * N);
scanf(«%s», c);

kondor ★★★

(18.09.08 20:55:34 MSD)

  • Показать ответ
  • Ссылка

Re: ошибка сегментирования

s/char *c/char *c[256/ к примеру.

Иначе происходит обращение по не инициализированному указателю.

  • Показать ответ
  • Ссылка

Re: ошибка сегментирования

Спасибо, помогло с malloc =)

anonymous

(18.09.08 21:20:15 MSD)

  • Показать ответ
  • Ссылка

Re: ошибка сегментирования

free(c) только не забудь сделать. И прочитать K&R заодно.

kondor ★★★

(18.09.08 21:33:20 MSD)

  • Ссылка

Re: ошибка сегментирования

нуб детектед

dilmah ★★★★★

(18.09.08 21:34:28 MSD)

  • Ссылка

Re: ошибка сегментирования

> scanf(«%s»,c);

За такое — расстрел на месте.

anonymous

(18.09.08 23:28:59 MSD)

  • Показать ответы
  • Ссылка

Re: ошибка сегментирования

> За такое — расстрел на месте.
Я все таки учусь… почему вместо того что бы помочь, многи начинают издеваться?

anonymous

(19.09.08 00:52:29 MSD)

  • Ссылка

Re: ошибка сегментирования

> За такое — расстрел на месте.
Я все таки учусь… почему вместо того что бы помочь, многи начинают издеваться?

anonymous

(19.09.08 00:53:00 MSD)

  • Показать ответы
  • Ссылка

Re: ошибка сегментирования

Это в большей степени относится к твоему первоисточнику/советчикам, провоцирующим написание заведомо небезопасного кода. Не принимай на свой счет.

anonymous

(19.09.08 02:03:43 MSD)

  • Ссылка

Re: ошибка сегментирования

Не правильней ли будет тут:
сalloc(N, sizeof(char));
И вообще есть ли разница между calloc и malloc, если делать
приведение типа в malloc или просто calloc для удобочитаемости?

borodun

(19.09.08 13:39:55 MSD)

  • Показать ответ
  • Ссылка

Re: ошибка сегментирования

calloc отличается от malloc только тем, что память нулями заполняет

Reset ★★★★★

(20.09.08 00:47:06 MSD)

  • Ссылка

Re: ошибка сегментирования

Нет такой функции в стандарте.
так надо делать:
char buf[256];
scanf(«%255s», buf);

Reset ★★★★★

(20.09.08 00:47:56 MSD)

  • Показать ответ
  • Ссылка

Re: ошибка сегментирования

На самом деле такая функция есть, но в msvc. Недавно по этому поводу в конторе с виндузятниками боролись, которые написали чего-то несобирающееся :)

Reset ★★★★★

(20.09.08 11:31:43 MSD)

  • Ссылка

Re: ошибка сегментирования

>scanf(«%s»,c);

scanf(«%s»,&c);

Об этом вроде в K&R говорится.

  • Показать ответ
  • Ссылка

Re: ошибка сегментирования

при работе со строками аперсанд неставится… вроде бы

anonymous

(21.09.08 22:57:27 MSD)

  • Ссылка

Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.

Похожие темы

  • Форум
    [нубский вопрос]C и указатели… (2009)
  • Форум
    Ошибка сегментирования в Cи «Баг или я дурак_2» (2012)
  • Форум
    ошибка сегментирования (2010)
  • Форум
    gcc, scanf. bug или кривые руки? (2008)
  • Форум
    Ошибка сегментирования при чтении из файла (2012)
  • Форум
    Си /*ошибка сегментирования */ (2009)
  • Форум
    Загадки при считывании scanf’ом в C (2016)
  • Форум
    [оффтопик][gcc][MinGW]Шозанах? О_о (2008)
  • Форум
    [элементарно][scanf][c]переполнение буфера (2009)
  • Форум
    Помогить отладить маленькую программку (segmentation fault) (2004)

The segmentation fault, also known as segfault, is a type of computer error that occurs whenever an unexpected condition causes the processor to attempt to access a memory location that’s outside its own program storage area. The term “segmentation” refers to a memory protection mechanism used in virtual memory operating systems.

This specific error arises because data is typically shared on a system using different memory sections, and the program storage space is shared among applications.

Segmentation faults are usually triggered by an access violation, which occurs when the CPU attempts to execute instructions outside its memory area or tries to read or write into some reserved address that does not exist. This action results in halting the current application and generates an output known as Segmentation Fault.

#1. What are the Symptoms of Segmentation Fault?

The symptoms of segmentation faults may vary depending on how and where they’re generated. Typically, this error is generated due to one of the following conditions:

#a. Dereferencing a null pointer

Programming languages offer references, which are pointers that identify where in memory an item is located. A null pointer is a special pointer that doesn’t point to any valid memory location. Dereferencing (accessing) null pointer results in segmentation faults or null pointer exceptions.

/**
 * @file main.c
 * @author freecoder
 * @brief this program allow to handle a segmentation fault error
 *
 * @version 1.0
 * @date 8 Jan. 2022
 *
 * @copyright Copyright (c) 2022
 *
 */
#include <stdio.h>

/* main program entry */
int main(int argc, char **argv)
{
	/* local variables */
	unsigned int *puiPointer = NULL;
	/* body program */
	*puiPointer = 20;
	return 0;
}

after compiling and running the program with the gdb command, the segmentation fault error appears:

➜  Article-XX gcc -g main.c -o main
➜  Article-XX ./main               
[1]    7825 segmentation fault  ./main
➜  Article-XX gdb ./main           
GNU gdb (Debian 10.1-1.7) 10.1.90.20210103-git
Copyright (C) 2021 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<https://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./main...
(gdb) start
Temporary breakpoint 1 at 0x401111: file main.c, line 20.
Starting program: /home/others/Article-XX/main 
warning: Error disabling address space randomization: Operation not permitted
Temporary breakpoint 1, main (argc=1, argv=0x7ffc9c096258) at main.c:20
20              unsigned int *puiPointer = NULL;
(gdb) list
15
16      /* main program entry */
17      int main(int argc, char **argv)
18      {
19              /* local variables */
20              unsigned int *puiPointer = NULL;
21
22              /* body program */
23
24              *puiPointer = 20;
(gdb) s
24              *puiPointer = 20;
(gdb) s
Program received signal SIGSEGV, Segmentation fault.
0x000000000040111d in main (argc=1, argv=0x7ffc9c096258) at main.c:24
24              *puiPointer = 20;
(gdb) 
segmentation fault Dereferencing a null pointer

#b. Trying to access memory not initialized

Programs using uninitialized variables may crash when attempting to access uninitialized memory or may expose data stored in the uninitialized variables by writing to them. Also in the case when the program attempts to read or write to an area of memory not allocated with malloc(), calloc() or realloc().

An example of a simple segmentation fault is trying to read from a variable before it has been set:

/**
 * @file main.c
 * @author freecoder
 * @brief this program allow to handle a segmentation fault error
 *
 * @version 1.0
 * @date 8 Jan. 2022
 *
 * @copyright Copyright (c) 2022
 *
 */
#include <stdio.h>

/* main program entry */
int main(int argc, char **argv)
{
	/* local variables */
	unsigned int *puiPointer;
	/* body program */
	*puiPointer = 20;
	return 0;
}

In this case, the pointer puiPointer will be pointing to a random location in memory, so when the program attempts to read from it (by dereferencing *puiPointer), a segmentation fault will be triggered:

➜  Article-XX gcc -g main.c -o main
➜  Article-XX gdb ./main           
GNU gdb (Debian 10.1-1.7) 10.1.90.20210103-git
Copyright (C) 2021 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<https://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./main...
(gdb) start
Temporary breakpoint 1 at 0x401111: file main.c, line 24.
Starting program: /home/others/Article-XX/main 
warning: Error disabling address space randomization: Operation not permitted
Temporary breakpoint 1, main (argc=1, argv=0x7fff6df4f038) at main.c:24
24              *puiPointer = 20;
(gdb) list
19              /* local variables */
20              unsigned int *puiPointer;
21
22              /* body program */
23
24              *puiPointer = 20;
25
26              return 0;
27      }
(gdb) s
Program received signal SIGSEGV, Segmentation fault.
0x0000000000401115 in main (argc=1, argv=0x7fff6df4f038) at main.c:24
24              *puiPointer = 20;
(gdb) 
segmentation fault - Trying to access memory not initialized

#c. Trying to access memory out of bounds for the program

In most situations, if a program attempts to access (read or write) memory outside of its boundaries, a segmentation fault error will occur. A code example of a simple segmentation fault error is below:

/**
 * @file main.c
 * @author freecoder
 * @brief this program allow to handle a segmentation fault error
 *
 * @version 1.0
 * @date 8 Jan. 2022
 *
 * @copyright Copyright (c) 2022
 *
 */
#include <stdio.h>

/* main program entry */
int main(int argc, char **argv)
{
	/* local variables */
	unsigned int uiArray[20];
	/* body program */
	uiArray[5000] = 1;
	return 0;
}

As shown bellow, the segmentation fault occurs after executing the out of bounds statement:

➜  Article-XX gcc -g main.c -o main
➜  Article-XX gdb ./main           
GNU gdb (Debian 10.1-1.7) 10.1.90.20210103-git
Copyright (C) 2021 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<https://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./main...
(gdb) start
Temporary breakpoint 1 at 0x401111: file main.c, line 23.
Starting program: /home/others/Article-XX/main 
warning: Error disabling address space randomization: Operation not permitted
Temporary breakpoint 1, main (argc=1, argv=0x7ffdb68620f8) at main.c:23
23              uiArray[5000] = 1;
(gdb) list
18      {
19              /* local variables */
20              unsigned int uiArray[20];
21
22              /* body program */
23              uiArray[5000] = 1;
24
25              return 0;
26      }
(gdb) s
Program received signal SIGSEGV, Segmentation fault.
main (argc=1, argv=0x7ffdb68620f8) at main.c:23
23              uiArray[5000] = 1;
(gdb) 
segmentation fault memory out of bounds

#d. Trying to modify string literals

/**
 * @file main.c
 * @author freecoder
 * @brief this program allow to handle a segmentation fault error
 *
 * @version 1.0
 * @date 8 Jan. 2022
 *
 * @copyright Copyright (c) 2022
 *
 */
#include <stdio.h>

/* main program entry */
int main(int argc, char **argv)
{
	/* local variables */
	char* pucString = "Sample String 1";
	/* body program */
	pucString[14] = '2';
	return 0;
}

As shown bellow, we got a segmentation error because the compiler put the string constant “Sample String 1” in read-only memory while trying to modify the contents of that memory which fails as a result:

➜  Article-XX gcc -g main.c -o main
➜  Article-XX gdb ./main           
GNU gdb (Debian 10.1-1.7) 10.1.90.20210103-git
Copyright (C) 2021 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<https://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./main...
(gdb) start
Temporary breakpoint 1 at 0x401111: file main.c, line 20.
Starting program: /home/others/Article-XX/main 
warning: Error disabling address space randomization: Operation not permitted
Temporary breakpoint 1, main (argc=1, argv=0x7ffc2ea212e8) at main.c:20
20              char* pucString = "Sample String 1";
(gdb) list
15
16      /* main program entry */
17      int main(int argc, char **argv)
18      {
19              /* local variables */
20              char* pucString = "Sample String 1";
21
22              /* body program */
23              pucString[14] = '2';
24
(gdb) n
23              pucString[14] = '2';
(gdb) 
Program received signal SIGSEGV, Segmentation fault.
main (argc=1, argv=0x7ffc2ea212e8) at main.c:23
23              pucString[14] = '2';
(gdb) 

segmentation fault modify string

#e. Using variable’s value as an address

A segmentation fault occurs when accidentally you are using a variable’s value as an address as you can see through the code example bellow:

/**
 * @file main.c
 * @author freecoder
 * @brief this program allow to handle a segmentation fault error
 *
 * @version 1.0
 * @date 8 Jan. 2022
 *
 * @copyright Copyright (c) 2022
 *
 */
#include <stdio.h>

/* main program entry */
int main(int argc, char **argv)
{
	/* local variables */
	int iVariable;
	/* body program */
	scanf("%d", iVariable);
	return 0;
}

As shown in the terminal consol bellow, the segmentation occurs after the scans statement:

➜  Article-XX gcc -g main.c -o main
➜  Article-XX gdb ./main           
GNU gdb (Debian 10.1-1.7) 10.1.90.20210103-git
Copyright (C) 2021 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<https://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./main...
(gdb) start
Temporary breakpoint 1 at 0x401135: file main.c, line 23.
Starting program: /home/others/Article-XX/main 
warning: Error disabling address space randomization: Operation not permitted
Temporary breakpoint 1, main (argc=1, argv=0x7fff418f9658) at main.c:23
23              scanf("%d", iVariable);
(gdb) list
18      {
19              /* local variables */
20              int iVariable;
21
22              /* body program */
23              scanf("%d", iVariable);
24
25              return 0;
26      }
(gdb) n
1
Program received signal SIGSEGV, Segmentation fault.
0x00007ff3e1d2201a in __vfscanf_internal (s=<optimized out>, format=<optimized out>, [email protected]=0x7fff418f9460, [email protected]=2)
    at vfscanf-internal.c:1895
1895    vfscanf-internal.c: No such file or directory.
(gdb) 
segmentation fault gemination fault using variable's value as address

#f. Stack overflow

The segmentation fault error may occur if the call stack pointer exceeds the stack bound in case of an infinite recursive function call:

/**
 * @file main.c
 * @author freecoder
 * @brief this program allow to handle a segmentation fault error
 *
 * @version 1.0
 * @date 8 Jan. 2022
 *
 * @copyright Copyright (c) 2022
 *
 */
#include <stdio.h>

/* main program entry */
int main(void)
{
	/* local variables */
	/* body program */
	main();
	return 0;
}

As shown bellow, the segmentation fault error happened, due to a stack oveflow after calling the main function:

➜  Article-XX gcc -g main.c -o main
➜  Article-XX gdb ./main                                
GNU gdb (Debian 10.1-1.7) 10.1.90.20210103-git
Copyright (C) 2021 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<https://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./main...
(gdb) start
Temporary breakpoint 1 at 0x40110a: file main.c, line 22.
Starting program: /home/others/Article-XX/main 
warning: Error disabling address space randomization: Operation not permitted
Temporary breakpoint 1, main () at main.c:22
22              main();
(gdb) list
17      int main(void)
18      {
19              /* local variables */
20
21              /* body program */
22              main();
23
24              return 0;
25      }
(gdb) n
Program received signal SIGSEGV, Segmentation fault.
main () at main.c:22
22              main();
(gdb) 

segmentation fault Stack overflow

#2. How do you Fix Segmentation Faults?

Because segmentation faults are often associated with memory management issues or problematic pointer assignments, they can be fixed by making sure that the target application correctly handles these errors and does not attempt to read or write memory locations outside its own address space.

There are also certain procedures which you can follow in order to prevent and fix segmentation faults:

#a. How to Prevent Segmentation Faults?

Most segmentation faults occur due to memory access errors, so it’s important to make sure that pointers used by an application always reference valid data areas.

  • Check the reference of null memory.
  • Testing the code with Valgrind or Electric Fence
  • Assert() before dereferencing a suspective pointer, mainly a pointer embedded in a struct that is maintained in a container in a list or an array.
  • Always remember to initialize pointers properly.
  • Protect shared resources against concurrent access in multithreading by using a mutex or a semaphore.
  • Use of free() routine

#b. How to Fix Segmentation Faults?

There are some tools that you can use in order to fix the segmentation faults:

  • Gdb and core dump file
  • Gdb and backtrace.
  • Debugfs and Dmesg for kernel debugging

Conclusion

A segmentation fault is generally caused by a programming bug that tries to access either non-existent or protected memory. It can also happen as a result of dividing an integer by zero (causing the program counter to be redirected to nowhere), accessing memory that is out of bounds at an address that does not contain valid data or code.

Finally, when enabled on some operating systems (and in some embedded programming environments), the processor may issue an exception if a memory address contains a non-mapped machine code instruction.

I hope this post has clarified what segmentation faults on the x86 architecture imply and how to avoid them. Do not forget to share the information on social networks if you believe it is useful for others. If you have any queries, please do not hesitate to leave a comment and subscribe to our newsletter. Best of luck with your coding and see you in the next article!

Понравилась статья? Поделить с друзьями:
  • Scan twain ошибка
  • Scan ksp ошибка
  • Scad ошибка при разложении матрицы 99
  • Sc899 00 ricoh ошибка
  • Sc819 00 ricoh ошибка