Thread: Dynamic memory allocation example

  1. #1
    Registered User
    Join Date
    May 2017
    Posts
    91

    Dynamic memory allocation example

    I have allocated dynamic memory for one integer variable

    Code:
    #include<stdio.h>#include<stdlib.h>
    int main (void)
    {    
        int *i = (int*)malloc(1 * sizeof(int)); 
        
        printf(" : %d \n", i);
        printf("%d \n", i,  *(i));
        printf(" %d \n", i,  &i); 
         
       return 0;
    }
    11406808
    11406808
    11406808

    if you look at the operator all they are the different * and &

    Why does all three operator give a same data ?

    updated : size 1
    Last edited by abhi143; 2 Weeks Ago at 07:35 AM.

  2. #2
    Registered User
    Join Date
    Feb 2019
    Posts
    534
    1st- You are not allocating "one" integer, but 5
    2nd- You are printf the same variable (i)
    3rd- You are getting warnings from your compiler and not paying attention to them.

  3. #3
    Registered User
    Join Date
    May 2017
    Posts
    91
    Quote Originally Posted by flp1969 View Post
    1st- You are not allocating "one" integer, but 5
    2nd- You are printf the same variable (i)
    3rd- You are getting warnings from your compiler and not paying attention to them.
    I think *i means data store at the address

    &i means address of data

    Both are different then why code gives same output ?

  4. #4
    Registered User
    Join Date
    Feb 2019
    Posts
    534
    Quote Originally Posted by abhi143 View Post
    I think *i means data store at the address

    &i means address of data

    Both are different then why code gives same output ?
    Take a good look at your printf() calls...

  5. #5
    Registered User
    Join Date
    May 2017
    Posts
    91
    Quote Originally Posted by flp1969 View Post
    Take a good look at your printf() calls...
    Am I missing %p to print the address ?
    Code:
    #include<stdio.h>
    
    #include<stdlib.h>
    
    
    int main (void)
    {    
        int *i = (int*)malloc(1 * sizeof(int)); 
         
        printf("%d \n", i);
        printf("%d \n", i,  *(i));
        printf("%p \n", i,  &i); 
          
       return 0;
    }
    12325800
    12325800
    00BC13A8

  6. #6
    Registered User
    Join Date
    Feb 2019
    Posts
    534
    Quote Originally Posted by abhi143 View Post
    Am I missing %p to print the address ?
    Well, yeah, but there is a another error... look closer... a little longer...
    Last edited by flp1969; 2 Weeks Ago at 10:16 AM.

  7. #7
    Registered User
    Join Date
    May 2017
    Posts
    91
    Quote Originally Posted by flp1969 View Post
    Nope... look closer... a little longer...
    Take a look at this
    Code:
    #include<stdio.h> 
    #include<stdlib.h>
     
    int main (void)
    {    
        int *i = (int*)malloc(1 * sizeof(int)); 
          
        printf("%d \n", i);
        printf("%d \n", *(i));
        printf("%p \n",  &i); 
           
       return 0;
    }

  8. #8
    Registered User
    Join Date
    Feb 2019
    Posts
    534
    Quote Originally Posted by abhi143 View Post
    Take a look at this
    Code:
    #include<stdio.h> 
    #include<stdlib.h>
     
    int main (void)
    {    
        int *i = (int*)malloc(1 * sizeof(int)); 
          
        printf("%d \n", i);
        printf("%d \n", *(i));
        printf("%p \n",  &i); 
           
       return 0;
    }
    See? Very easy to spot, isn't it?
    Now some considerations:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main( void )
    {
      // You don't need to use type casting here, malloc() will return a "generic" pointer to void, always.
      int *i = malloc( sizeof( int ) );
    
      printf( "%p\n", i );  // Use %p to specify the argument is a pointer.
      printf( "%d\n", *i ); // Will print the integer pointed by i, but you know it is uninitialized, don't you?
      printf( "%p\n", &i ); // This will make the compiler allocate 'i' on stack (so you can get the "adddress of" i.
                            // You'll get the address of 'i', not the address of the dynamic block allocated.
    
      // Not really necessary, but it is a good pratice to do a little housekeeping.
      free( i );
    }
    Compiling and running:
    Code:
    $ cc -o test test.c
    $ ./test
    0x55a7d5516260
    0
    0x7ffc8f1c66a0
    It is only a coincidence *i is zero, could be anything...

  9. #9
    Registered User
    Join Date
    May 2017
    Posts
    91
    Quote Originally Posted by flp1969 View Post
    See? Very easy to spot, isn't it?
    It is only a coincidence *i is zero, could be anything...
    we have allocated memory space for variable i

    If I want to assign the value to variable What I have to do

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,181
    Quote Originally Posted by abhi143
    we have allocated memory space for variable i
    You could say that, but it would be more accurate to say that you allocated memory for what i points to.

    Quote Originally Posted by abhi143
    If I want to assign the value to variable What I have to do
    Just remember that since i is a pointer to int, *i is an int, so you assign to the int variable as you would any other int variable:
    Code:
    *i = 123;
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    Registered User
    Join Date
    May 2017
    Posts
    91
    Quote Originally Posted by laserlight View Post
    You could say that, but it would be more accurate to say that you allocated memory for what i points to.

    Just remember that since i is a pointer to int, *i is an int, so you assign
    correct
    Code:
    #include<stdio.h> #include<stdlib.h>
     
    int main (void)
    {    
        int *i = (int*)malloc(1 * sizeof(int)); 
        
        *i = 123;
          
        printf("%d \n", i);
        printf("%d \n", *(i));
        printf("%p \n",  &i); 
           
       return 0;
    }
    output
    10949544
    123
    0061FF2C

    Now If I want to assign value to array

    I can't write
    Code:
    array[5] = {1,2,3,4,5}; //static array
    How to assign array value
    Code:
     #include<stdio.h>#include<stdlib.h>
    
    
    int main (void)
    {
        int size = 5, i=0;
        
        int *array= (int*)malloc((sizeof(int)) * size);
    
    
        for(i=0; i < size; i++)
        {
       
     
        }  
       return 0;
    }

  12. #12
    Registered User
    Join Date
    Feb 2019
    Posts
    534
    Quote Originally Posted by abhi143 View Post
    Now If I want to assign value to array
    Use the operador [] or the operator *:

    Code:
    int *p;
    
    p = malloc( size * sizeof( int ) );
    for ( i = 0; i < size; i++ )
      p[i] = K;    // OR *(p + i) = k;

  13. #13
    Registered User
    Join Date
    May 2017
    Posts
    91
    Quote Originally Posted by flp1969 View Post
    Use the operador [] or the operator *:

    Code:
    int *p;
    
    p = malloc( size * sizeof( int ) );
    for ( i = 0; i < size; i++ )
      p[i] = K;    // OR *(p + i) = k;
    No let's suppose we have allocated 5 memory location using malloc

    we want to assign following values to each memory location

    memory location 0 = 5
    memory location 1 = 15
    memory location 2 = 5
    memory location 3 = 53
    memory location 4 = 101

    How can we do that ?

  14. #14
    Registered User
    Join Date
    Aug 2019
    Location
    Inside a Singularity
    Posts
    118
    No let's suppose we have allocated 5 memory location using malloc

    we want to assign following values to each memory location

    memory location 0 = 5
    memory location 1 = 15
    memory location 2 = 5
    memory location 3 = 53
    memory location 4 = 101

    How can we do that ?
    The same way you'd initialise a normal array.

    Code:
    p [0] = 5;
    p [1] = 15;
    p [2] = 5;
    p [3] = 53;
    p [4] = 101;
    I'm not sure if you can do this with malloc but by using the new keyword in C++, you can provide an initialiser list.
    Code:
    int* p = new int [5] { 5 , 15 , 5 , 53 , 101 };
    list initialization (since C++11) - cppreference.com

    As your doubt is posted in the C Programming section and new is part of C++, you probably wouldn't wanna be doing that and so you may do a normal index by index initialisation. If you were to take input from the user for initialization, you could:
    Code:
    for (int i = 0; i < Size; i++)
    {
         // Take input at the i'th index the way it's done in C
    }
    Last edited by Zeus_; 2 Weeks Ago at 11:12 AM.

  15. #15
    Registered User
    Join Date
    Feb 2019
    Posts
    534
    If you want to initialize a bunch of elements of dynamically allocated array you can do as @Zeus_ told you:
    Code:
    p[0] = 5;
    p[1] = 15;
    p[2] = 5;
    p[3] = 53;
    p[4] = 101;

    Or, in C (not C++), with a compiler capable of compiling code compliant to ISO 9989:2011 standard (I am not sure, right now, but I believe ISO 9989:1999 already had compound literals), you can use compound literals, as in:
    Code:
    int *p = malloc( 5 * sizeof( int ) );
    memcpy( p, (int []){ 5, 15, 5, 53, 101 }, 5 * sizeof( int ) );
    Notice is easier to just simply do:
    Code:
     int a[] = { 5, 15, 5, 53, 101 };
    But you are asking how to inicialize a dynamic allocated buffer!
    Last edited by flp1969; 2 Weeks Ago at 12:53 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to add dynamic memory allocation
    By JJ57663 in forum C Programming
    Replies: 1
    Last Post: 04-26-2019, 07:07 PM
  2. dynamic memory allocation
    By abhi143 in forum C Programming
    Replies: 12
    Last Post: 10-09-2018, 07:22 AM
  3. C dynamic memory allocation
    By Romyo2 in forum C Programming
    Replies: 4
    Last Post: 06-03-2015, 07:04 AM
  4. Dynamic memory allocation
    By Luciferek in forum C++ Programming
    Replies: 118
    Last Post: 10-02-2008, 11:34 AM
  5. Dynamic memory allocation
    By amdeffen in forum C++ Programming
    Replies: 21
    Last Post: 04-29-2004, 08:09 PM

Tags for this Thread