-1

the following program gives output 4. I thought it will output 8 sizeof(int) + sizeof(unsigned int)

#include<stdio.h>
#include<stdlib.h>
int main()
{
        struct node
        {
                int a;
                struct node * next;
        };
        struct node * p= (struct node *) malloc( sizeof( struct node));
        printf("%d", sizeof( p));
}
bhavneet
  • 51
  • 2
  • 11

3 Answers3

2

In this code, p is a pointer, so you're just printing the size of a pointer (which is apparently 4 bytes in your compiler/OS combination). If you want the size of the structure, you need to print sizeof(*p). Also, as was pointed out, using "%d" for a size_t won't necessarily work ("%zu" is correct, although %d will on most compilers/OSs in the real world). Also, you shouldn't assume that the size of the structure "should" be 8. Pointers might be bigger, or the compiler might want to pad or align the structure in some odd way.

Lee Daniel Crocker
  • 12,927
  • 3
  • 29
  • 55
1

p is just a pointer. Its size depends on ABI, which is in your case 4.

Maroun
  • 94,125
  • 30
  • 188
  • 241
Atmaram Shetye
  • 993
  • 7
  • 15
1

And the correct answer: your output, if any, is indeterminate, because you're using the wrong format specifier in the call to printf(). You should have used %zu instead - sizeof() yields an object of type size_t.

Thus, your program invokes undefined behavior, and it's free to do (and print) anything it wants to.

  • I believe converting an unsigned int to int will not result in undefined behavior. It might convert some thing like 255 into something like -127 on 8 bit systems. Not sure though. A source to the undefined behaviour would be greatly appreciated! – Atmaram Shetye Jun 23 '13 at 06:34
  • 1
    The point is that `sizeof(x)` doesn't yield an `unsigned int`, it yields a `size_t`. On most systems, that's the same as an `unsigned int`, but it's not required to be. `%zu` is the proper format specifier for a `size_t`, whereas `%d` may cause terrible things to happen. – amalloy Jun 23 '13 at 06:44