I want to write a small program, which, by user input through argv, gets a segmentation error. I am quite new to C but I think the following code does the job:
int main(int argc, char *argv[])
{
int bufferSize;
char * buffer[100];
unsigned int i;
if (argc > 1) {
bufferSize = atoi(argv[1]);
for (i = 0; i < bufferSize; ++i)
*( buffer + i ) = i;
}
return 0;
}
My idea is that the program intialize (?) a pointer to a buffer of a specific size. If the user then input a number larger then the buffer size it will write to uninitialized memory, hence get a seg. fault. Is this reasoning correct whatsoever?
Ps. When compiling,I get a assignment makes pointer from integer without a castwarning, can someone maybe tell me why that happens? Thanks
The most traditional way to purposely get a segmentation fault, that I’ve seen, is to write to
NULL, e.g. something like:You can use a command line argument as a simple boolean value to see if this should be done or not.
Note that writing to
NULLis not actually guaranteed to cause a crash, it’s simply undefined behavior so basically anything could happen (including causing nasal demons).The warning is because you have an array of pointers, and try to assign an integer to a pointer in the array.