Thread: Having difficulty to understand pointers

  1. #1
    Registered User
    Join Date
    Feb 2020
    Posts
    23

    Having difficulty to understand pointers

    Hi,

    I am having difficulty to understand pointers in c language

    I wrote my own code

    Code:
    #include<stdio.h> 
    
    #include<stdlib.h>
             
    int main ()
    {  
     
     int *p = NULL;
     p = malloc (sizeof(*p));
     
     if (p == NULL)
     {
         printf("Memory is not allocated \n");
     }
     
     else 
     {
        printf("Memory is allocated \n");
        
        *p = 20;
        
        printf(" address = %p \n", p);
         
        printf(" content = %d \n", *p);
     }
     
     free(p);
            
      return 0;     
    }
    address = 007313A8
    content = 20

    1. Does it means that the pointer p points to the address 007313A8 where there are 20 stores ?

    2. Is line number 8 a null pointer?

    3. Is line number 27 a dangling pointer?

  2. #2
    Registered User
    Join Date
    Feb 2019
    Posts
    671
    1- A pointer variable holds an address which points to a single memory location. malloc() alocates (reserves) a block of memory and returns the address of the first byte;

    2- Yes... The NULL constant translate to (void *)0. The address "zero" is a NULL pointer (ISO 9989:9999+ 6.3.2.3-3);
    You could archive the same result if you do:
    Code:
    p = 0;
    3- You are freeing the block of memory previously allocated by malloc(). At this point, after callind free(), p will hold an address of unallocated memory, which can be treated as "invalid". But there is no memory leakage here. In this context, you can think of p as dangling...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Difficulty with understanding recursion and pointers
    By mdt0322 in forum C Programming
    Replies: 3
    Last Post: 08-01-2013, 08:13 PM
  2. Understand pointers
    By Aphex in forum C Programming
    Replies: 3
    Last Post: 08-12-2010, 09:07 PM
  3. i cant understand something in pointers
    By nik2 in forum C Programming
    Replies: 2
    Last Post: 02-12-2010, 01:26 PM
  4. Trying To Understand Pointers!
    By pobri19 in forum C Programming
    Replies: 4
    Last Post: 05-08-2008, 01:28 AM
  5. Something I still don't understand about pointers
    By Extol in forum C++ Programming
    Replies: 11
    Last Post: 03-01-2003, 06:20 AM

Tags for this Thread