Does Declaring a Pointer Allocate Memory in C?

Question: Can a Pointer in C Automatically Allocate Memory When it is Declared

Answer: As we know Pointer is like any ordinary variable in that when it is declared, compiler allocates it a location in memory. Every location has an address and contents. The contents of a pointer is, however, address; address of some ordinary variable, other pointer or some function etc.. For example:

/* 
 * mem_alloc_to_ptr.c -- Program shows memory is allocated to ptr when
 * declared 
 */
#include <stdio.h>
int main(void)
{
    int *ip, *ip1;  /* pointer to integer declared */
    int boys = 100; /* boys an int is initialized to 100 */
    ip = &boys;     /* ip holds the address of boys */
 
    printf("\nAddress of pointer to integer \"ip\" in exp. \"ip = &boys\" "
           "is %p\nand its contents, an address is %p\nand value it points"
           " to is %d\n", &ip, ip, *ip);
 
    printf("\npointer to integer \"ip1\" is declared but not initialized..."
           "\n");
    printf("Its Address in memory %p\nits contents, garbage address %p\n", 
           &ip1, ip1);
    /* contents of ip1 is garbage address */
 
    printf("\n");
    return 0;
}

Above program when I run on my Linux system produces output as:

Address of pointer to integer "ip" in exp. "ip = &boys" is 0x7fffb7807088
and its contents, an address is 0x7fffb780707c
and value it points to is 100
 
pointer to integer "ip1" is declared but not initialized...
Its Address in memory 0x7fffb7807080
its contents, garbage address 0x7fffb7807170

Notice that even if a pointer is declared but not initialized, it holds Garbage address. Be sure not to dereference an uninitialized pointer!

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

advertisement
advertisement
If you wish to look at all C Tutorials, go to C Tutorials.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.