Home > Enterprise >  How to cause a seg fault on purpose
How to cause a seg fault on purpose

Time:10-28

Allocate a dynamic variable using malloc() increment that count until a seg fault occurs. Then print out the memory addresses until the fault occurs so that the faulting address is output.

Note address should be printed before the access that causes the seg fault.

This is what I have tried so far. So far it seems it runs indefinitely.

#include <stdio.h>
#include <stdlib.h>
int main(){
    char * ptr = malloc(1);
    while(1){
        printf(" Address is %p\n", ptr  );
    }
    return 0;
}

CodePudding user response:

Although this is not an answer to the actual question, it is an answer to what others may expect to find here after reading the question from the title.

The best way of getting a program to cause a segmentation fault, is to specifically send the process itself the SIGSEGV signal:

#include <sys/types.h>
#include <unistd.h>
#include <signal.h>

int main(void) {
    kill(getpid(), SIGSEGV);
}

Note that the kill function is poorly named, it should be seen as "send signal to process".

CodePudding user response:

The following fixes your issue:

Note that accessing unallocated memory is poor practice and this should be seen purely as an educational example, and not as good code.

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

int main(void) {
    unsigned char *ref = malloc(1);
    unsigned char *ptr = ref;

    while (ptr  ) {
        printf("%p (offset %lu)", ptr, ptr - ref);
        fflush(stdout);
        printf(": x\n", *ptr);
    }
}

I have split up the printf call into two parts, with a fflush in-between. This is to "guarantee" that the memory address (and its offset to the malloc call) are output, before it is accessed.

Otherwise, you would see the last address that did get accessed successfully.

The second printf accesses the memory and prints its byte value. This is the call that actually could cause the segmentation fault. The first one should not, because you are not accessing the actual memory, but note that you should not have arbitrary memory pointers flying around.

  •  Tags:  
  • c
  • Related