C Program to save address of a pointer in a variable



C Program to save address of a pointer in a variable and some malloc examples

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

void main()
{
    /*******************************************************************************
     * C program to save the 'address of a pointer' in a 'variable'.
     *******************************************************************************/
    int a1;
    int *b = &a1;
    /* variable 'c' to store a pointer's address. */
    long int c;
    c = (long int)b;
    printf("%p\n", (void *)c);
    printf("0x%lx \n", c);

    /*******************************************************************************
     * C program to save the 'address of pointer' in a variable and
     * free the address saved in the variable, by using that variable, instead
     * of original pointer.
     *******************************************************************************/
    int *ptr = NULL;
    ptr = (int *)malloc(100 * sizeof(int));
    long int g = (long int)ptr;
    printf("ptr: 0x%lx  g:0x%lx \n", (long int)ptr, g);
    free((int *)g);
    ptr = NULL;

    printf("ptr: 0x%lx  g:0x%lx \n", (long int)ptr, g);

    /********************************************************************************
     * C program to validate if we write to heap memory beyond allocated heap memory.
     * ONE SHOULD NEVER DO THAT, BUT THIS JUST FOR SAKE OF EXPERIMENTATION
     ********************************************************************************/
    char *ptr_1 = NULL;
    ptr_1 = (char *)malloc(10 * sizeof(char));
    strcpy(ptr_1, "neelkanth3neelkanth3neelkanth3neelkanth3neelkanth3neelkanth3neelkanth3");

    printf("ptr_1 : %s\n", ptr_1);


  /******* memcpy and malloc  ********************************/
    char *x = NULL;
    /* total allocated size is 14 bytes.  */
    x = (char *)malloc(14 * sizeof(char));
    memcpy(x, "1234", sizeof("1234"));
    memcpy(x+4, "neelkanth", sizeof("neelkanth"));

    printf("the malloced string is :%s \n", x);

    /*******************************************************************/


    return ;
}

Output:

0x7ffe0b07e45c
0x7ffe0b07e45c
ptr: 0xb85010  g:0xb85010
ptr: 0x0  g:0xb85010
ptr_1 : neelkanth3neelkanth3neelkanth3neelkanth3neelkanth3neelkanth3neelkanth3
the malloced string is :1234neelkanth