realloc doesnt re -allocate memory specified???

Discussion in 'C' started by shakisparki, Apr 5, 2011.

  1. shakisparki

    shakisparki New Member

    Joined:
    Mar 30, 2011
    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    please why doesnt realloc give the exact amount of bytes i specified??

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
       int size ,counter = 0 ;
       int *memoPtr ;
       int  *newMemoPtr;
       printf("Enter Size of Array > "); scanf("%d" , &size);
    
       memoPtr = (int *)calloc( size, sizeof(int));
    
       if (memoPtr != NULL){
    
           while (counter < size)
           {
               scanf("%d" , &memoPtr[counter++]);
           }
       }
       else{
        printf("Memory couldnt be allocated");  }
    
        for (counter = 0; counter < size ; counter++){
            printf("%d , " , memoPtr[counter]);}
    
        memoPtr = (int*) realloc(memoPtr , (size / 2) * sizeof(int));
        printf("\n");
    
        for (counter = 0; counter < size ; counter++){
            printf("%d , " , memoPtr[counter]);}
    
    
    }
     
    Last edited by a moderator: Apr 5, 2011
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    What is the number of bytes you are specifying and how many bytes you think it has allocated?
     
  3. ASRRAJ

    ASRRAJ New Member

    Joined:
    Jun 13, 2008
    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    memoPtr = (int*) realloc(memoPtr , (size / 2) * sizeof(int));
    check this statment ...do you really need this size/2
     
  4. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    Don't be a smartass. YOU are asking US for help, therefore you don't know what you're doing, and we do. So if we ask questions, answer them even if you think they're irrelevant.

    Have another look at the loop at the end of the program.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice