Hello

Hello,

I'm translating some C code to Delphi and found something that surprise me...is it logical that this code compiles ?

{code}
#include
#include

void test();

void test2() {
test();
}

void test(char *msg) {
printf("test called '%s' (%d)\n", msg, strlen(msg));
}

void main() {
test2();
}
{code}

and the result is
test called 'test' (4)

tested with gcc under Ubuntu

thanks

Comments

  1. pretty weird, tested gcc on mac, it builds, with some warnings

    testc.c:11:42: warning: format specifies type 'int' but the argument has type 'unsigned long' [-Wformat]
    printf("test called '%s' (%d)\n", msg, strlen(msg));
    ~~ ^~~~~~~~~~~
    %lu
    testc.c:14:1: warning: return type of 'main' is not 'int' [-Wmain-return-type]
    void main() {
    ^
    testc.c:14:1: note: change return type to 'int'
    void main() {
    ^~~~
    int

    nothing about calling test without an arg

    running the build results in:

    Segmentation fault: 11

    ReplyDelete
  2. note that I've put the call to test() in test2() because a direct call from main() raise an error "too few argements to function 'test'"

    ReplyDelete
  3. yes, saw it, on my end, it looks like it's using clang, regardless, it builds tho it shouldn't

    ReplyDelete
  4. You declared both the prototype and the call as taking no parameters. Then you declared the body of the function as taking a pointer.

    If there's a compiler bug, it would be either:

    (1) not complaining that the declaration of test with a non-empty argument list hides or in some way overrides the one with an empty argument list; or

    (2) that it is using the version of test with an argument and creating a stack frame with an implied argument while calling the function that takes zero arguments.

    Given how loosey-goosey the c programming language has always been when it comes to various kinds of undocumented "shorthand notations", this doesn't surprise me a bit.

    Interestingly, Pascal has allowed you to call procs defined with parameter lists with a call having no parameters forever. Try it in Delphi ... it might not even generate hint or warning.

    ReplyDelete
  5. This is C, everything compiles. ;-)
    Your function prototype test, which is used for the call in test2, does not have a parameter, so it compiles. Then it gets redefined as having a parameter. This should cause a compile error, but since it is never called after the definition, it apparently doesn't.

    ReplyDelete
  6. Daniela Osterhagen So a linker issue then.

    ReplyDelete

Post a Comment