how to find the size allocated by malloc

Discussion in 'C' started by naveenrai88, Jul 20, 2008.

  1. naveenrai88

    naveenrai88 New Member

    Joined:
    Jun 17, 2008
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    Hi,
    following is the code that i wrote: :happy:
    Code:
    #include <stdio.h>
    int main()
    {
            int *ptr;
            ptr = (int *)malloc(256*256*256*256-1);
            printf("Sizeof int is %d\n", sizeof(int));
            if(ptr == NULL)
                    printf("Allocation failed");
            else
                    printf("Allocation succedded");
            return 1;
    }
    
    i ran this code on gcc complier. now the warning that i get is
    *************************
    try.c: In function ‘main’:
    try.c:6: warning: incompatible implicit declaration of built-in function ‘malloc’
    try.c:6: warning: integer overflow in expression
    try.c:6: warning: integer overflow in expression
    ***************************

    Q 1) since the sizeof (int) =4 so why integer overflow warning is being displayed???
    Q 2) how can i calculate the size of the memory chunck allocated by the malloc function????
    ( if i write "ptr = (int *)malloc(256*256*256*256+1000);" even though, i get these warnings and get the output of the program as "Allocation succedded: ):surprised
    Kindly explain why am i getting the output as mentioned above even though the value mentioned in malloc is overflowing the unsigned int range.. :cryin:

    thanks in advance
     
    Last edited by a moderator: Jul 20, 2008
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    Why do you want to allocate 4GB of RAM? Are you on a 64-bit system?
    Think about how you might represent 256*256*256*256+1000 in 32 bits.
    Also think about how 256*256*256*256-1 might be represented, and what the value of the MSB will be, and what malloc will do if it's asked to allocate a negative amount of memory.
     

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