Passing static array to C variadic function

Daniel Murphy via Digitalmars-d digitalmars-d at puremagic.com
Tue Jul 22 02:01:37 PDT 2014


"Daniel Gibson"  wrote in message news:lql6ec$1rqk$1 at digitalmars.com...

> >
> > printf("Hello %s\n", "segfault");
>
> If the compiler did the right thing for extern (C) functions (i.e. 
> implicitly passing "segfault" by reference), this shouldn't cause a 
> segfault.

Whether or not passing the point to the C function is the right thing 
depends on your perspective.

Old D code (from the 32-bit only days) used to do this successfully:

printf("Hello %.*s\n", "segfault");

So it relied on both the length and pointer being passed.  Unfortunately 
this was done quite a lot, so simply changing the rules so string literals 
get passed to C varargs as pointers would silently (and horribly) break this 
code.

Giving an error and forcing you to be explicit about what exactly you wanted 
is the best that's possible.

> Well, that printf("%s", "asdf"); doesn't work (really?) and that I have to 
> pass static arrays  arr.ptr in varargs, is much more surprising/unexpected 
> than having to casts class objects to void* when passing them to a C 
> function.

That is an error because it was causing bugs, usually when porting C++ code 
which looks exactly the same.  I've never seen a bug with passing a class 
handle to printf. 



More information about the Digitalmars-d mailing list