At what point does segfault happen?

Does the following segault code in array [10] = 22 or array [9999] = 22?
I'm just trying to figure out if all the code will execute before it is eliminated. (in C language).

#include <stdio.h>
int main(){

int array[10];
int i;
for(i=0; i<9999; ++i){
    array[i] = 22;
}    
return 0;    
}
+3
source share
8 answers

It depends ... If the memory after the array [9] is empty, nothing can happen until you reach the memory segment that is busy.

Try the code and add:

 printf("%d\n",i);

in a loop and you will see when it works and burns out. I get various results: from 596 to 2380.

+13
source

Use

$ gcc -g seg.c -o so_segfault
$ gdb so_segfault
GNU gdb 6.8-debian
Copyright (C) 2008 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 "i486-linux-gnu"...
(gdb) run
Starting program: /.../so_segfault 
Program received signal SIGSEGV, Segmentation fault.
0x080483b1 in main () at seg.c:7
7       array[i] = 22;
(gdb) print i
$1 = 2406
(gdb) 

, , , segfault i. , , >= 10, i, , : , . , [222] ( ), , = 222, >= 10.

+9

. C , . undefined. , , , - . .

, , :

  • , , segfault. , , . .
  • , , . , , , , .
  • , - . , , , , .

: . C , , , .

+8

. , .

array - , 10 * sizeof(int) . , , i array. printf, . , i = 10, array[10] = 22 clobbers i, - array[23].

, , . , , 9999 .

array ( malloc()), SIGSEGV, . 10- . . , malloc , SIGSEGV, , .

+4

segfault, , , . , segfault i == 10. , , , . , , , , segfault.

, , , , . - - ( , ), , , , , segfault. ( , , , .)

.

+3

, . == 10 .. . , , () ( ). segfault = 10-9999 .

+2

More generally, you can find out where a segmentation error occurs on Linux systems using the debugger. For example, to use gdb, compile your program using debugging symbols using the -g flag, for example:

gcc -g segfault.c -o segfault

Then call gdb with your program and any arguments using the -args, .g flag:

gdb --args ./segault myarg1 myarg2 ...

Then, when the debugger starts, enter run, and your program should work until it receives SIGSEGV, and should tell you where it was in the source code when it received this signal.

0
source

Source: https://habr.com/ru/post/1709526/


All Articles