0

Consider the below code snippet:

#include <stdio.h>

int main()
{
    int p = malloc( sizeof( int ) );
    return 0;
}

The above program compiles successfully without any warning.

Shouldn't it give error/warning as address of memory chunk is being stored in integer variable rather than a pointer?

Initially, i believed that the behavior is strange because i forgot to include stdlib. Soon, my assumption failed. The behavior is same even after including stdlib.

See the below program after including stdlib

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int p = malloc( sizeof( int ) );
    return 0;
}

This program has also the similar behavior.

Why it compiles successfully?

Green goblin
  • 9,898
  • 13
  • 71
  • 100

2 Answers2

1

It compiles succesfully but you should receive a warning :

> gcc -o test test.c
test.c: In function ‘main’:
test.c:6:13: warning: initialization makes integer from pointer without a cast [enabled by default]

You should never discard compiler warnings. I used gcc 4.7 without any options.

Kwariz
  • 1,306
  • 8
  • 11
0

malloc() is returning a void * type. What you're returning and storing in to that int is the address of the void *. This is a perfectly legal thing to do, if for example you wanted to printf the address of the malloc'ed memory before using it you could:

int main()
{
    int *r = NULL;
    int p = malloc( sizeof( int ) );
    printf("%#x\n",p);
    r = (int *)p; 
    *r = 5;
    printf("%d\n", *r);
    free(r);
    return 0;
}

Obviously this doesn't really make a lot of sense... but there's a reason for not getting an error when using this code. As far as a warning goes... you should have gotten one.

VS gives:

1>c:\users\ma\documents\visual studio 2010\projects\test\test\test.c(7): warning C4047: 'initializing' : 'int' differs in levels of indirection from 'void *' 
Mike
  • 47,263
  • 29
  • 113
  • 177