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

Garrett Cooper yanefbsd at gmail.com
Thu May 13 02:45:15 UTC 2010


On May 12, 2010, at 6:54 PM, Mike Meyer wrote:

> On Wed, 12 May 2010 17:30:48 -0400
> Garrett Cooper <yanefbsd at gmail.com> wrote:
> 
>> 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
> 
> It isn't off by one. argv is a pointer to pointers to char, so *argv
> is a pointer to char, and so is *(argv+1). In the latter case, it
> increments by the size of a pointer, so *(argv+1) is the same as
> argv[1]. You're confusing the issue by having argv[0] and argv[1] be
> copies of the same string. If you make argv[1] something_else, you
> get:
> 
> bhuda% ./test_fstat something_else
> argc - 2, argv[0] - ./test_fstat
> something_else - 3745212532062
> 
> Your real bug is that you never allocate the buffer you passed to
> fstat. You need to declare sb without the "*", and then pass &sb to
> fstat and reference sb.st_size. With what you've got, fstat will write
> the stat results across whatever address is on the stack space
> allocated to the pointer sb.
> 
> Removing the test and increment (which one?) will move the code
> around, potentially changing the value of the pointer sb, both of
> which will cause a different part of memory to be clobbered by the
> call to fstat, meaning things will blow up in a different way.

	Yup ... as pointed out on the list elsewhere, that was my fault by not properly allocating the storage for the pointer to the struct stat object. Silly me for not realizing it sooner.
Thanks for the help :),
-Garrett


More information about the freebsd-hackers mailing list