argv offset -- doesn't make sense...

Garrett Cooper yanefbsd at gmail.com
Wed May 12 21:30:43 UTC 2010


Hi Hackers,
	Ignoring the compiler warning (yes, I know...), why is the offset for the argv[0] (program name) in the following program off by one? It doesn't make sense why the fstat would work, but the printf would fail (and in fact segfault if I remove the 1 < argc guard statement and adjusted the offset by removing the +1).
Thanks,
-Garrett

PS I know I'm missing all of the real error checks because I just wanted a quick and dirty test app.

# gcc -Wall -O0 -g -o test_fstat test_fstat.c
test_fstat.c: In function 'main':
test_fstat.c:20: warning: format '%lu' expects type 'long unsigned int', but argument 3 has type 'off_t'
# ./test_fstat ./test_fstat
argc - 2, argv[0] - ./test_fstat
(null) - 7118
# ./test_fstat ./test_fstat
argc - 2, argv[0] - ./test_fstat
./test_fstat - -790036480
# cat test_fstat.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>

int
main(int argc, char **argv)
{
	if (1 < argc) {
		printf("argc - %d, argv[0] - %s\n", argc, *argv);
		int fd = open(*(argv+1), O_RDONLY);
		struct stat *sb;
		fstat(fd, sb);
		printf("%s - %ld\n", *(argv+1), (long int) sb->st_size);
	}
	return 0;
}


More information about the freebsd-hackers mailing list