Thread: malloc call

  1. #1
    Registered User
    Join Date
    Jan 2011
    Posts
    1

    malloc call

    Can somebody explain to me what does (1<<20) mean in below code.
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    int main (void) {
            int n = 0;
            char *p;
    
            while (1) {
                    if ((p = malloc(1<<20)) == NULL) {
                            printf("malloc failure after %d MiB\n", n);
                            return 0;
                    }
                    memset (p, 0, (1<<20));
                    printf ("got %d MiB\n", ++n);
            }
    }
    Last edited by Salem; 01-26-2011 at 01:27 AM. Reason: Added [code][/code] tags - learn to use them yourself

  2. #2
    Registered User \007's Avatar
    Join Date
    Dec 2010
    Posts
    179
    It shifted the bit 20 to the left. 2^20 = 1048576 which is one MB. I guess it mallocs 1 mb of space for p. If the malloc fails then it returns NULL, which the statement also checks for.
    Last edited by \007; 01-25-2011 at 10:01 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling C in Visual Studio 2005
    By emanresu in forum C Programming
    Replies: 3
    Last Post: 11-16-2009, 04:25 AM
  2. DIfference between , and ;
    By rocketman03 in forum C++ Programming
    Replies: 6
    Last Post: 10-21-2009, 09:46 AM
  3. malloc + segmentation fault
    By ch4 in forum C Programming
    Replies: 5
    Last Post: 04-07-2009, 03:46 PM
  4. Troubleshooting Input Function
    By SiliconHobo in forum C Programming
    Replies: 14
    Last Post: 12-05-2007, 07:18 AM
  5. Is malloc() a system call on UNIX?
    By Waiting_11 in forum C Programming
    Replies: 4
    Last Post: 10-29-2002, 11:51 AM