Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting string from main() arguments

Tags:

c

I am trying to create a pointer to one of the main() arguments in my program. I set up the initial pointer, then I set it equal to the 2nd element in the array, but I get an error when I try to compile, segmentation fault. Does this occur because a pointer is pointing to a bad address?

Here is the code:

char *filename;
*filename = argv[1];
printf("The filename is: %s", *filename);

I get errors about the pointer trying to cast the argument as an int. Is this because the pointer is actually an integer address value and I am trying to set it equal to a string?

Edit: When I change to "filename = argv[1]", then I get the following error from my compiler: assignment discards qualifiers from pointer target type.

like image 988
Kelp Avatar asked Apr 05 '11 23:04

Kelp


3 Answers

A segmentation fault couldn't possibly occur when you compile. Unless, well, the compiler violates memory safety, which is unlikely. I'll take it that it happens when you run the program :D.

The problem is here:

*filename = argv[1];

It should be:

filename = argv[1];

Why? You declared a pointer to char, unitialized, poiting nowhere in particular. Then, you dereferenced that pointer and assigned data to that memory position. Which is, well, who knows where!

Edit: you also dereference filename in the printf() call. Remove that * :).

Also, didnt' the compiler shoot a warning when you assigned *filename? Making integer from pointer without a cast, would be my guess? Pay attention to the warnings, they provide useful information!

Cheers.

like image 154
slezica Avatar answered Nov 10 '22 23:11

slezica


You're not making filename point to the same place as argv[1]. To do that you need

filename = argv[1];

With your version (*filename = argv[1];) you're trying to make whatever filename points to have the value that is in argv[1]. There's lots of stuff wrong with this: a) filename is not initialized and can point anywhere, even invalid locations; b) argv[1] is of type char* and you're trying to put it into a location of type char!

like image 4
pmg Avatar answered Nov 10 '22 23:11

pmg


In the statement *filename = argv[1];, the expression *filename attempts to dereference (find the value pointed to) the filename pointer, which is not yet pointing anywhere meaningful.

Change the assignment to filename = argv[1].

like image 3
John Bode Avatar answered Nov 10 '22 22:11

John Bode