0

A few questions about this simple scenario:

#include <unistd.h>
#include <stdio.h>

void empty(){};

int main()
{
    printf("%p\t%lu\n", empty, sizeof(empty));
    write(1, empty, 100);

    return 0;
}

What exactly is happening when I use the function's name as a reference?

It shows size of one but printf still treats it as a pointer and yet a void pointer is of size 8. Additionally, onto the write function:

Essentially I want to replicate the printf %p writing the value of a memory address rather than the value at that address mainly to get a better handle on how this all works :^)

Thanks!

Mr. B
  • 9
  • 2
  • 2
    Function pointers are special that way, don't treat them as normal pointers. – Some programmer dude Aug 30 '15 at 21:10
  • 4
    `%p` formats a `void*` pointer. Function pointers can’t be safely cast to `void*`, so you’re using `printf` wrong and it doesn’t actually work. You also can’t use `sizeof` on function pointers: [“The sizeof operator shall not be applied to an expression that has function type” (6.5.3.4)](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf) – Ry- Aug 30 '15 at 21:28
  • A `long long` also most times has a size of `8`. Still different types. What is the point? – too honest for this site Aug 30 '15 at 21:30
  • 2
    C11 says (§6.5.3.4 The `sizeof` and `_Alignof` operators): _Constraints: The `sizeof` operator shall not be applied to an expression that has function type or an incomplete type, to the parenthesized name of such a type, or to an expression that designates a bit-field member._ Compiling with GCC and `-pedantic`, I get: `pedantic.c:9:46: error: invalid application of ‘sizeof’ to a function type [-Werror=pointer-arith]`. Incidentally, `write()` is declared in ``, not ``. – Jonathan Leffler Aug 30 '15 at 21:34
  • @minitech so what value is it printing? – Mr. B Aug 30 '15 at 21:35
  • @Olaf It being a pointer and returning void I thought there'd be some correlation. Irregardless I was only confused. – Mr. B Aug 30 '15 at 21:37
  • On most machines, `sizeof(void (*)(void)) == sizeof(void *)`, so the compiler makes a conversion and prints a value which is more or less OK. There are systems (IBM AS/400, which are now call iSeries, IIRC) where that is not the case — a function pointer is 128 bits, but ordinary pointers are only 64 bits. – Jonathan Leffler Aug 30 '15 at 21:37
  • 2
    @JonathanLeffler Alright that provides some clarity. I definitely need to read the standard and continue experimenting. Thanks again. – Mr. B Aug 30 '15 at 21:46
  • Related: http://stackoverflow.com/q/10932910/694576 – alk Aug 31 '15 at 10:53

0 Answers0