Thread: Use of malloc and realloc

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    28

    Use of malloc and realloc

    Hello everyone,
    i am studying dynamic memory allocation in c,which can be done by using malloc calloc and realloc.
    But still i don't understand the concept.
    for eg
    int *p;
    p=(int*)malloc(100);
    allocates 100 int size for p;

    but if i don,t do p=(int*)malloc(100), *p is pointing to p we can always do p[i] and enter whatever values we want to store.
    so what is actually happening at p=int*malloc(100);

    also i found some example of using realloc and the too work fine if i remove the reallocating part.

    someone help!!!

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by mrbains View Post
    Hello everyone,
    i am studying dynamic memory allocation in c,which can be done by using malloc calloc and realloc.
    But still i don't understand the concept.
    for eg
    int *p;
    p=(int*)malloc(100);
    allocates 100 int size for p;

    but if i don,t do p=(int*)malloc(100), *p is pointing to p we can always do p[i] and enter whatever values we want to store.
    so what is actually happening at p=int*malloc(100);

    also i found some example of using realloc and the too work fine if i remove the reallocating part.

    someone help!!!
    Actually if you don't use malloc in your int* p example, p is pointing to nothing, contains a garbage value and should not be used. As for treating it like an array such as p[10]... what if your pointer is indexing the stack? You could end up overwriting crucial registers and return addresses, crashing your system in the process.

    What malloc(), calloc() and realloc() do is provide your pointer with safe and protected memory to put your data into. Creating an array as p[100] includes a memory reservation that protects that memory for you.

  3. #3
    Registered User
    Join Date
    Sep 2007
    Posts
    1,012
    but if i don,t do p=(int*)malloc(100), *p is pointing to p we can always do p[i] and enter whatever values we want to store.
    This is not true. First, *p is not pointing anywhere. p is a pointer, *p would be an int. If you don't assign a value to p, it has an indeterminate value, which in practical terms means it contains garbage. If you assign to p[0], you get undefined behavior. It might crash, it might not. It might do what you expect, it might not. Regardless of what happens, it is bad code.
    so what is actually happening at p=int*malloc(100);
    Memory is being allocated, and p is being pointed there. This should actually be something like:
    Code:
    p = malloc(100 * sizeof *p);
    Otherwise you're just asking for 100 bytes, not 100 ints. That isn't inherently wrong, but it's not especially useful in general.

    Anyway, p is now pointing to a block of space large enough to hold 100 ints. When you access this memory, it's not undefined, as it is if you don't allocate space. I suspect you're confused because things “worked” when you didn't allocate, so what's the point in allocating? You have to get used to the fact that C will happily let you do all sorts of bad things, and sometimes things will appear to work. That doesn't mean the code is correct.

  4. #4
    Registered User
    Join Date
    Oct 2010
    Posts
    28
    Thanks for the knowledge

    so i tried to use it and wrote this code for a dynamic size stack kind of thing...

    Code:
    #include<stdio.h>
    
     int *a;
     int top=0;
     int s=0;
    
    int push(int i)
    {
     if(top==s)
      {printf("\nStack full");
       return 0;
       }
       a[top]=i;
       ++top;
    }
    int pop()
     {if(top==0)
       {printf("\n\nStack empty");
        (void)getchar();
        exit(0);
        }
        --top;
    
    }
    
    main()
    { int c,x,j,p=1,n;char ch='y';
      printf("\nEnter size of stack..\n");
      scanf("%d",&s);
      a=(int *)malloc(s*(sizeof(int)));
    
    
     while(ch=='y')
     {printf("\t\t\t\nenter\n1.push\n2.pop");
      scanf("%d",&c);
      if(c==1)
      {printf("\nenter no of items");
       scanf("%d",&n);
       getchar();
       for(j=0;j<n;j++)
       {printf("\nEnter:");
       scanf("%d",&x);
       p=push(x);
         if(p==0)
         { printf("\n\nNow reallocating.\t Press Enter\n\n");
           (void)getchar();
           a=realloc(a,2*(s*(sizeof(int))));
           p=1;
           s=s*2;
           push(x);
         }
    
       }
       printf("\n\n\t\t\tnow stack:");
       for(j=top-1;j>=0;--j)
       printf("\n%d",a[j]);
      }
    
      if(c==2)
      {pop();
      printf("\n\t\t\tnow stack");
      for(j=top-1;j>=0;--j)
      printf("\n%d",a[j]);
      }
      getchar();
      printf("\n\nmore???");
    
      scanf("%c",&ch);
      }
      }
    so am i using malloc() and realloc() as one should.
    And where should i use free()?.why and what do we free???

  5. #5
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Call free(a) after your code has completed everything it does using a.

    Given that your allocations and reallocations occur in main(), one appropriate place to do that is at the end of main() - just before the last closing brace.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  6. #6
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    When do we use free? Well... as soon as you are done with a dynamic variable.
    What do we free? Whatever we've created.

    For every malloc or calloc call you need a corresponding free.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc, realloc..wat on earth!
    By zesty in forum C Programming
    Replies: 3
    Last Post: 12-21-2007, 01:42 PM
  2. malloc and realloc
    By jayfriend in forum C Programming
    Replies: 4
    Last Post: 01-05-2007, 02:25 PM
  3. malloc, realloc
    By figo2476 in forum C Programming
    Replies: 3
    Last Post: 04-28-2006, 10:11 PM
  4. Linked list versus malloc and realloc.
    By Bajanine in forum C Programming
    Replies: 2
    Last Post: 06-20-2005, 08:08 PM
  5. malloc and realloc
    By odysseus.lost in forum C Programming
    Replies: 3
    Last Post: 05-27-2005, 08:44 AM

Tags for this Thread