473,772 Members | 2,513 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem Outputting Command Line Arguments from argv

Hello. I'm having a very strange problem that I would like ot check
with you guys.

Basically whenever I insert the following line into my programme to
output the arguments being passed to the programme:

printf("\nComma nd line arguement %d: %s.", i , argv[i] );

The porgramme outputs 3 of the command line arguements, then gives a
segmentation fault on the next line, followed by other strange
behaviour.

Does outputting the command line arguments change them or some other
aspect of the programme somehow? The programme runs fine when I
comment the line out, which just makes no sense to me!

Kind Regards,

Matt

Jul 19 '07 #1
17 3380
On Thursday 19 Jul 2007 4:34 pm, Matt <ma*****@hotmai l.comwrote in
message <11************ **********@m3g2 000hsh.googlegr oups.com>:
Hello. I'm having a very strange problem that I would like ot check
with you guys.

Basically whenever I insert the following line into my programme to
output the arguments being passed to the programme:

printf("\nComma nd line arguement %d: %s.", i , argv[i] );

The porgramme outputs 3 of the command line arguements, then gives
a segmentation fault on the next line, followed by other strange
behaviour.

Does outputting the command line arguments change them or some
other aspect of the programme somehow? The programme runs fine when
I comment the line out, which just makes no sense to me!
In C arrays begin at subscript zero and end at subscript N-1, for an
array of N elements. The argv array is an array of char *. The
number of elements in this array is given by the first argument to
main, traditionally called as argc. So when printing out the program
arguments, you must iterate through the argv array from subscript
zero up to and including subscript argc-1. argv[argc] is a null
pointer. Passing a null pointer to most functions that expect a
valid pointer value causes undefined behaviour.
Jul 19 '07 #2
Matt <ma*****@hotmai l.comwrites:
Hello. I'm having a very strange problem that I would like ot check
with you guys.

Basically whenever I insert the following line into my programme to
output the arguments being passed to the programme:

printf("\nComma nd line arguement %d: %s.", i , argv[i] );

The porgramme outputs 3 of the command line arguements, then gives a
segmentation fault on the next line, followed by other strange
behaviour.

Does outputting the command line arguments change them or some other
aspect of the programme somehow? The programme runs fine when I
comment the line out, which just makes no sense to me!
That line looks ok (except that you probably should have the "\n" at
the end of the ouput line and you misspelled "argument", and the '.'
character at the end of the line can cause confusion, but those aren't
relevant to your real problem). In other words, you've shown us
exactly the portion of your code that *isn't* relevant to the problem
you're having.

If I had to guess, I'd say you probably have something like:

for (i = 1; i <= argc; i ++) {
/* your printf call here */
}

On the last iteration of the loop, you attempt to print the value of
argc[argc], which is guaranteed to be a null pointer.

Or the problem might be something else entirely; I'm only guessing.

If you had posted your actual code (copy-and-paste the entire program,
which you've trimmed down to something big enough to exhibit the
problem but small enough to be easy for us to analyze), then I
wouldn't have had to guess.

Just another wild guess: did you remember the required
'#include <stdio.h>'?

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jul 19 '07 #3
The relevant part of my code reads as follows:

for ( i = 0 ; i < argc ; i++ )

{

printf("\narg = %d\n" , argc );

printf("\nComma nd line arguement %d: %s. \n", i , *argv[i] );

and the stdio.h header is loaded at the start. You may notice I have
added a * before the argv[i] as I realised I wished to print the value
the pointer points at, was this a correct thing to do?

Something else that is rather worrying is that if I comment this bit
out, the next time the programme tries to read argv[1], I get another
segmentation fault. I assume this only happens when argv[1] = NULL,
but since I am almost certain the programme to supplied with at least
one argument, and that the error occurs when I try to print argv[0]
(which is the one thing that cannot be NULL!), something else must be
wrong here.

Kind Regards,

Matt
Jul 22 '07 #4
Matt wrote, On 22/07/07 23:45:
The relevant part of my code reads as follows:
How do you know the relevant part if you don't know what the problem is?
for ( i = 0 ; i < argc ; i++ )

{

printf("\narg = %d\n" , argc );

printf("\nComma nd line arguement %d: %s. \n", i , *argv[i] );

and the stdio.h header is loaded at the start. You may notice I have
added a * before the argv[i] as I realised I wished to print the value
the pointer points at, was this a correct thing to do?
Did you actually try running it? If so it would have failed because argv
is a char**, so argv[i] is a char*, so *argv[i] is a char and %s expects
a pointer to a string, not a single character.
Something else that is rather worrying is that if I comment this bit
out, the next time the programme tries to read argv[1], I get another
segmentation fault. I assume this only happens when argv[1] = NULL,
but since I am almost certain the programme to supplied with at least
one argument, and that the error occurs when I try to print argv[0]
(which is the one thing that cannot be NULL!), something else must be
wrong here.
You have a bug. However, if you do not show your real code no one can
show you your real bug.
--
Flash Gordon
Jul 22 '07 #5
Matt wrote:
>
The relevant part of my code reads as follows:

for ( i = 0 ; i < argc ; i++ )

{

printf("\narg = %d\n" , argc );

printf("\nComma nd line arguement %d: %s. \n", i , *argv[i] );

and the stdio.h header is loaded at the start. You may notice I have
added a * before the argv[i] as I realised I wished to print the value
the pointer points at, was this a correct thing to do?

Something else that is rather worrying is that if I comment this bit
out, the next time the programme tries to read argv[1], I get another
segmentation fault. I assume this only happens when argv[1] = NULL,
but since I am almost certain the programme to supplied with at least
one argument, and that the error occurs when I try to print argv[0]
(which is the one thing that cannot be NULL!), something else must be
wrong here.
/* BEGIN new.c */

#include <stdio.h>

int main(int argc, int *argv[])
{
int i;

printf("\narg = %d\n\n", argc);
if (argc 1) {
for (i = 0; i != argc; ++i) {
printf("Command line arguement %d:%s\n", i, argv[i]);
}
} else {
puts("This program displays command line arguments.");
for (i = 0; *argv != NULL; ++argv) {
printf("Command line arguement %d:%s\n", i, *argv);
}
}
return 0;
}

/* END new.c */

--
pete
Jul 22 '07 #6
Matt <ma*****@hotmai l.comwrites:
On Jul 23, 12:07 am, Keith Thompson <ks...@mib.orgw rote:
[...]
>Other relevant parts of your code are the declaration of 'main', the
declaration of 'i', and so so forth. In other words, given the code
you posted, it shouldn't be difficult to write and post a complete
program. It probably doesn't make much difference in this case, but
in general posting compilable code makes it a lot easier for us to
help.

I wish I could, but sadly the programme in its entirely is huge and is
split up into many different source files.
Sure you can.
troublesome code arises from my implementation of the
getopt_long function from the GNU library:

http://www.gnu.org/software/libc/man...t-Long-Options...

with the example code:

http://www.gnu.org/software/libc/man...t-Long-Option-...

My implemtation is as follows:

for ( i = 0 ; i < argc ; i++ )
[big snip]
}
The code you're having trouble with is accessing argc and argv. Just
narrow it down to something that accesses argc and argv in the same
way, but doesn't call anything non-standard (for example, anything
that refers to getopt), while still exhibiting the same problem. Make
sure the resulting program compiles and links; it needs to include a
declaration of main, for example.

Quite possibly you'll figure out the problem while doing this. If
not, post it and we can help you.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jul 23 '07 #7
Quite possibly you'll figure out the problem while doing this. If
not, post it and we can help you.
I'll give that a go.

In the meantime, DDD now reports that with my present code, the
segmentation fault occurs when I call the getopt_long function in the
above code:

"*getopt_va l = getopt_long (argc, argv, "c:", long_options,
&option_index); "

Is this another example of where I shouldn't have used a *?

Kind Regards,

Matt

Jul 23 '07 #8
Having made a test programme as follows for printing argc and argv to
the screen:

"// A programme to test argc and argv

// Load function libraries

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

// Main function

int main(int argc , char **argv)

{

int i; // DO loop index

// Print out argc and argv to screen

for ( i = 0 ; i < argc ; i++ )

{

printf("argc = %d\n",argc);
printf("argv[0] = %s\n",argv[0]);

}

}"

I had no errors, so calling the functions themselves doesn't seem the
be the problem.

I have since gone and commented out the getopt_long code I had added
and reintroduced the original code I had to read in the arguments:

" for ( i = 0 ; i < argc ; i++ ) // argc is the number of commmand
line arguements passed to the programme.

{

// Compare first two characters from command line arguement. If
they match, return 0 and execute statement.
if (!( strncmp( argv[i] , "-c" , 2 )))

{

sprintf( config_file , "%s" , argv[ i+1 ] ); // Point programme
to a new config file by changing the
// config_file string to the argument following "-c".

}"

Interestingly, the programme now works flawlessly as it did before,
which clearly indicates the code I posted earlier for the getopt_long
code is the cause of my errors. I will endeavour to produce another
test programme to try and replicate the segmentation fault and post
back later.

Thanks for all the excellent responses so far.

Kind Regards,

Matt

Jul 23 '07 #9
I have just tried running the code given from the GNU Example page,
and as I should have expected, the code was fine.

Now when I put my own implementation of this code (which is of course
very similar) by itself, I got a segmentation fault whenever I put in
an argument such as "-c" or "-stack" that the programme is meant to
recognise and act upon. The problem does not occur if I use "c" or
"stack":

// A programme to test my implementation of the getopt_long function
in an independant environment from the main programme

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

static int stack_mode = 0;

int main( int argc , char *argv[] )

{

extern int stack_mode;

char *getopt_val;
int i;

opterr = 0;

printf("argc = %d\n",argc);

for ( i = 0 ; i < argc ; i++ )

{

printf("argv[%d] = %s\n",i,argv[i]);

}

for ( i = 0 ; i < argc ; i++ ) // argc is the number of command line
arguments passed to the programme.

{

while (1)

{

static struct option long_options[] =

{

// These options set a flag.
{"stack" , no_argument , &stack_mode , 1}, // Enable stack
(convolution) mode

// These options don't set a flag. We distinguish them
by their indices.
{"configfile " , required_argume nt , 0 , 'c'},
{0 , 0 , 0 , 0}

};

// getopt_long stores the option index here.
int option_index = 0;

getopt_val = getopt_long (argc, argv, "c:", long_options,
&option_inde x);

// Detect the end of the options.
if (getopt_val == -1)

{

break;

}

switch (*getopt_val)

{

case 0:
/* If this option set a flag, do nothing else now. */
if ( long_options[option_index].flag != 0)

{

break;

}

printf ("option %s", long_options[option_index].name);

if (optarg)

{

printf (" with arg %s", optarg);

}

printf ("\n");
break;

case 'c':
printf ("option -c with value `%s'\n", optarg);
break;

case '?':
/* getopt_long already printed an error message. */
break;

default:
abort ();

}

}

/* Print any remaining command line arguments (not options). */
if (optind < argc)

{

printf ("non-option ARGV-elements: ");

while (optind < argc)

{

printf ("%s ", argv[optind++]);

}

putchar ('\n');

}

}

}

I have tried replacing "case 'c':" with "case '-c':" and so forth in
the case statements starting on line 92, but the source code would not
compile.

Kind Regards,

Matt

Jul 23 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
388
by: Ashe Corven | last post by:
i need help pretty bad for this from the command line >csend string1 4233 "string2" how can i copy string1, or string2 to a char* or a string. for argument 4 (string2)
7
2320
by: qazmlp | last post by:
void func() { // Is it by anyway possible to read the value of the first command line parameter i.e. argv here ? } int main() { func() ; // No command line arguments are passed to func(). }
2
5682
by: Julian | last post by:
I would like to have output from my program to be written to cout as well as a file. (actually, i want several other output options but this should explain my problem in the simplest way). I have seen commercial programs print output to the screen as well as to a log file. depending on the user and other situations, i might want to turn off one of the outputs or maybe even both outputs. so, i want a single line with operator << function...
2
4200
by: SunRise | last post by:
Hi I am creating a C Program , to extract only-Printable-characters from a file ( any type of file) and display them. OS: Windows-XP Ple help me to fix the Errors & Warnings and explain how to use Command-Line Arguments inside C program.
13
2811
by: Sree | last post by:
If the program (myprog) is run from the command line as myprog 1 2 3 , What would be the output? main(int argc, char *argv) { int i; for(i=0;i<argc;i++) printf("%s",argv); }
40
2748
by: raphfrk | last post by:
I have a program which reads in 3 filenames from the command line prog filename1 filename2 filename3 However, it doesn't work when one of the filenames has spaces in it (due to a directory name with a space in it) because that filename gets split into 2. I tried
16
2722
by: John Salerno | last post by:
Here's my new project: I want to write a little script that I can type at the terminal like this: $ scriptname package1 where scriptname is my module name and any subsequent arguments are the names of Linux packages to install. Running the script as above will create this line: sudo aptitude install package1 package2 ...
0
2029
by: raa abdullah | last post by:
Overview A conflict-serializbility\recoverability checker, SCR, is a program that takes in a schedule and outputs 2 decisions: Conflict serialzable or Not confilict serializable AND Recoverable or Not recoverable. The following is a detailed description of the program. Input The input to SCR should be a schedule of operations. It should be in a text file (.txt) where each line is in the following format: Operation TransactionNum ...
4
2993
by: neha_chhatre | last post by:
please let me know if am using command line arguments, how to send arguments to a C program if i am working on ubuntu say for example suppose name of my program is prog.c if argc=3 then how to send those three arguments(pt1.txt,pt2.txt,pt3.txt) to prog.c through command prompt if i am working on linux
0
10106
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10039
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9914
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8937
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7461
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6716
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5484
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3610
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2851
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.