Why does this NOT give a violation of segmentation?

The code below gives a segmentation violation:

#include <stdio.h> 
#include <string.h> 

void function(char *str) {
   char buffer[16];

   strcpy(buffer,str);
}

int main() {
  char large_string[256];
  int i;

  for( i = 0; i < 255; i++)
    large_string[i] = 'A';

  function(large_string);
  return 1;
}

Compiled and works as follows:

gcc -Wall -Wextra hw.cpp && a.exe

But nothing happens.

Note

The above code really rewrites the ret address, etc., if you really understand what is happening under it.

The ret address will be 0x41414141to be specific.

Attention! This requires deep stack knowledge.

+3
source share
10 answers

. , ( ). , , , . , , large_string.

+6

, buffer large_string . , strcpy buffer, large_string, . 255 , , , , large_string ( large_string). , , - .

fluke function . buffer , , , , , , . , , :-). , .

, , segfault, , . undefined. , .

[Edit: (GCC cygwin), x86 /. segfault.]

+3

.cpp(++), gcc ( g++)... , , Linux (, Windows - . exe), , , :

/tmp/ccSZCCBR.o:(. eh_frame + 0x12): undefined `__gxx_personality_v0 ' collect2: ld 1

+2

UB (undefined). Strcpy , , .

+1

undefined, , . , .

, - , - () ( / /...), . , , .

+1

, strcpy(), , . strlen(buffer) . undefined.

strlcpy(3) .

+1

:

#include <stdlib.h>
int main() {
    int *a=(int *)malloc(10*sizeof(int));
    int i;
    for (i=0;i<1000000; i++) a[i] = i;
    return 0;
}

SIGSEGV = 37000! ( gdb).

, malloc... mallocs, , , . :

gcc -g -Wall docore.c -o c -lefence

SIGSEGV , i=10, .

+1

, undefined. , , undefined undefined.

, . . , () . ().

+1

, , , i. , , , - , , , - large_string , i, 0 255. , - , . , large_string 256 257 .

, , , . , , , , strcpy, , , - -.

, , "undefined" "".

+1

char [16] ' , \0. strcpy copy, \0 - , 16 .

0

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


All Articles