![]() |
Causing a Seg Fault on Purpose
Hi, I'm trying to learn C coding and I happen to be at a chapter in a book I'm reading which deals with segmentation faults. What I'm trying to do is get a program, that accepts command-line arguments, to crash (with a seg fault) when it isn't given any arguments. The code from the book is as follows:
convert2.c :
When I compile this code in gcc (v4.1.3) on Ubuntu 7.10 I get this message: $ gcc -g -o convert2 convert2.c convert2.c: In function ‘usage’: convert2.c:5: warning: incompatible implicit declaration of built-in function ‘exit’ It still compiles, but when I run it, it does this: $ ./convert2 Repeating 0 times... Since I'm trying to break the program, this isn't the result I want. Does anyone know how to "break" this program so that it will cause a seg fault? BTW, the desired result would be this: $ ./convert2 Segmentation fault (core dumped) $ |
Re: Causing a Seg Fault on Purpose
>What I'm trying to do is get a program, that accepts command-line
>arguments, to crash (with a seg fault) when it isn't given any arguments. What you're seeing is undefined behavior. It might crash, it might not. In this case, accessing argv[2] doesn't touch memory outside of your address space, and when atoi fails, it returns 0. Both of these are undefined behavior, but you lucked out in that it doesn't cause the error you were expecting. The only way to guarantee a seg fault is to raise it yourself. |
Re: Causing a Seg Fault on Purpose
:
#include <stdlib.h>will get rid of the warning about exit being implicitly defined to get a seg fault you should just try writing to a specific memory address. something along the lines of: :
int *i;i think that would generate a seg fault. |
Re: Causing a Seg Fault on Purpose
There are lots of things that will generate seg faults -- division by 0 if another one of them
:
int x = 123 / 0; |
Re: Causing a Seg Fault on Purpose
Out of curiosity, any particular reason you want to cause a seg fault? It is an odd request...
|
Re: Causing a Seg Fault on Purpose
:
#include <signal.h> |
Re: Causing a Seg Fault on Purpose
Quote:
|
Re: Causing a Seg Fault on Purpose
Quote:
|
Re: Causing a Seg Fault on Purpose
This sounds like a good idea for a game -- 100 ways to create a seg fault :)
|
Re: Causing a Seg Fault on Purpose
Quote:
|
| All times are GMT -5. The time now is 4:09 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC