Thread: Malloc not allocating anything.

  1. #1
    Registered User
    Join Date
    Nov 2015
    Posts
    7

    Question Malloc not allocating anything.

    Hello!

    I have an assignment to create datablocks of the sizes 100mb, 200,300..1000.

    And its worth mentioning, im noob at C :P

    Now my code looks like this:

    Code:
    #include <stdio.h>#include <stdlib.h>
    #include <time.h>
    #include <sys/time.h>
    #include <assert.h>
    #include <unistd.h>
    #define KILO    1024
    #define MEGA (KILO*KILO)
    #define INCREMENT 100
    
    int diffTime(struct timeval * startTime, struct timeval * endTime) {
        return ((endTime->tv_sec - startTime->tv_sec)*1000 + (endTime->tv_usec- startTime->tv_usec)/1000);
    }
    
    
    
    
    
    
    int createDataBlock(long int storlek) {
        char * str;
        str = (char *) malloc(storlek);
        //free(str);
        return 1;
    }
    
    
    int main(void) {
        long int i;
        struct timeval startT, endT;
        struct timezone tzp;
        for(i=INCREMENT;i<=50000;i=i+INCREMENT){
            gettimeofday(&startT, &tzp); /* hämta starttid */
            createDataBlock(i);
            gettimeofday(&endT, &tzp); /* hämta sluttid */
            printf("Datablock  %ld MB took %d msek\n",i, diffTime(&startT,&endT));
            //sleep(3);
            //printf("Tiden: %d", timeDiff);
        }
    
    
        return 0;
    }

    Why isnt any memory being allocated, and how would one save the allocated memory to disk(to a file) if possible ?

    PS: I just want to fill it with random data, I was hoping malloc would fill it with garbage ?

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,729
    You allocate a total of almost 12 MiB. Maybe that's smaller than you though. Other than that, the allocation should work.

    PS: I just want to fill it with random data, I was hoping malloc would fill it with garbage ?
    From your perspective, it's garbage. But it might not be, it depends whether the OS chooses to clear the memory before it passes it to you.
    Devoted my life to programming...

  3. #3
    Registered User talahin's Avatar
    Join Date
    Feb 2015
    Posts
    51
    So, you allocate a datablock and assign it to a variable that will get lost when the function returns. Also you don't check if the memory really got allocated in the first place.

    Cheers.

  4. #4
    Registered User
    Join Date
    Nov 2015
    Posts
    7
    Quote Originally Posted by GReaper View Post
    You allocate a total of almost 12 MiB. Maybe that's smaller than you though. Other than that, the allocation should work.


    From your perspective, it's garbage. But it might not be, it depends whether the OS chooses to clear the memory before it passes it to you.
    Why do I only allocate 12 MiB ? The variable i, that I pass as an argument to createDatablock shoulde allocate 5000 MiB ? Im confused.


    talahin
    So, you allocate a datablock and assign it to a variable that will get lost when the function returns. Also you don't check if the memory really got allocated in the first place.

    Cheers.


    Yeah, ive commented out the /free, to see if there is going to be any diffrences, anyways, how would one check if it really got allocated anyways ? I was looking on the "top" command

  5. #5
    Registered User
    Join Date
    Sep 2015
    Location
    Australia
    Posts
    63
    Hi..

    Did you check the return values for the malloc() , if there is an issue with the allocation it returns a NULL....so test against a NULL..
    And why are you using a Return 1 ....that generally indicates an error .

  6. #6
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,729
    Your for loop has an "i" as counter that counts from 100 to 50000, with an increment step of 100. Each time, you pass that "i" to "createDataBlock()" which allocates that amount of bytes and returns without freeing them. The total amount of bytes that would be allocated can be found by doing the addition:
    100 + 200 + 300 + ... + 50000
    which is equivalent to:
    (1 + 2 + 3 + ... + 500)*100
    which is in turn equivalent to:
    (501*500/2)*100
    Devoted my life to programming...

  7. #7
    Registered User
    Join Date
    Nov 2015
    Posts
    7
    Quote Originally Posted by GReaper View Post
    Your for loop has an "i" as counter that counts from 100 to 50000, with an increment step of 100. Each time, you pass that "i" to "createDataBlock()" which allocates that amount of bytes and returns without freeing them. The total amount of bytes that would be allocated can be found by doing the addition:
    100 + 200 + 300 + ... + 50000
    which is equivalent to:
    (1 + 2 + 3 + ... + 500)*100
    which is in turn equivalent to:
    (501*500/2)*100
    Aha...

    So I gotta write something like this to get it in MiB;

    str = (char *) malloc((storlek*1000));

    And, how would one save this to a file ? I know how to open a file, but how would I save this garbage data to it ?

    PS, tested it, I wrote the code like this:

    Code:
    int createDataBlock(long int storlek) {    
        char * str;
        str = (char *) malloc((storlek*1000));
        //free(str);
        if(str != NULL){
            printf("not NULLZ, SIZE IS %d", (int)sizeof(str));
        }
        else{
            printf("NULLZ");
        }
        return 0;
    }
    And the output I get is:

    not NULLZ, SIZE IS 8Datablock 49100 MB tog 0 mseknot NULLZ, SIZE IS 8Datablock 49200 MB tog 0 msek
    not NULLZ, SIZE IS 8Datablock 49300 MB tog 0 msek
    not NULLZ, SIZE IS 8Datablock 49400 MB tog 0 msek
    not NULLZ, SIZE IS 8Datablock 49500 MB tog 0 msek
    not NULLZ, SIZE IS 8Datablock 49600 MB tog 0 msek
    not NULLZ, SIZE IS 8Datablock 49700 MB tog 0 msek
    not NULLZ, SIZE IS 8Datablock 49800 MB tog 0 msek
    not NULLZ, SIZE IS 8Datablock 49900 MB tog 0 msek
    not NULLZ, SIZE IS 8Datablock 50000 MB tog 0 msek
    (I just copied the last ones)

    Why is the size only 8 :s
    Last edited by Jozef; 11-24-2015 at 06:01 AM.

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,833
    Quote Originally Posted by Jozef
    I just want to fill it with random data, I was hoping malloc would fill it with garbage ?
    "The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate". Indeterminate effectively means "garbage", but "garbage" does not mean "random". If you are required to fill the elements of the array with random data, then you should do so properly, e.g., by making use of the pseudorandom number facilities provided by the standard library, or some other PRNG, or with the help of some source of randomness.

    Quote Originally Posted by Jozef
    And, how would one save this to a file ? I know how to open a file, but how would I save this garbage data to it ?
    As the data is in a binary format, not text stored in a null terminated string, you should use the relevant functions to print to the file, e.g., fwrite. printf is meant for text.

    Quote Originally Posted by Jozef
    Why is the size only 8 :s
    The size of the pointer to char is 8 bytes for you.
    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

  9. #9
    Registered User
    Join Date
    Nov 2015
    Posts
    7
    Quote Originally Posted by laserlight View Post
    "The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate". Indeterminate effectively means "garbage", but "garbage" does not mean "random". If you are required to fill the elements of the array with random data, then you should do so properly, e.g., by making use of the pseudorandom number facilities provided by the standard library, or some other PRNG, or with the help of some source of randomness.


    As the data is in a binary format, not text stored in a null terminated string, you should use the relevant functions to print to the file, e.g., fwrite. printf is meant for text.


    The size of the pointer to char is 8 bytes for you.
    Alrighty, but I still have no idea how to solve my problem...

    The thing is, I should start with allocating 100mb, then 200mb, then 300mb, up to 2gb, to see the time diffrence when the system starts to use swapping (when RAM is full)...

    My current code is :

    Code:
    int createDataBlock(long int storlek) {   
        char * str;
        str = (char *) malloc((storlek*MEGA));
        
        if(str != NULL){
            printf("NOT NULLZ");
        }
        else{
            printf("NULLZ");
        }
        //free(str);
        return 0;
    }

    And I use i<3000.
    I use free -h and I see this (please note the program is still running because I use while(1){} )

    total used free shared buffers cachedMem: 2,4G 2,2G 198M 10M 166M 919M
    -/+ buffers/cache: 1,1G 1,3G
    Swap: 2,4G 0B 2,4G
    But when I look on the VIRT column in top, I see:
    20,512g

    So, it allocates memory? But still, when using free-h, I cant see that it even touched the swap memory ? and, it takes it 0msek to allocate such memory which I dont belive is true.
    Last edited by Jozef; 11-24-2015 at 06:00 AM.

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,833
    Quote Originally Posted by Jozef
    Alrighty, but I still have no idea how to solve my problem...
    I gave an example of a function to use. Read up on it.

    Remember to free what you malloc.
    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
    Nov 2015
    Posts
    7
    Quote Originally Posted by laserlight View Post
    I gave an example of a function to use. Read up on it.

    Remember to free what you malloc.
    I updated my reply above, since I wasnt finished posting it when I did, sorry for that.

    And yeah, but shouldnt the system start using swap by-itself ?
    I shouldnt be the one that writes the if mem == full, write to disk/use swapping, right ?

  12. #12
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,110
    Assuming you're using Linux (you need to say what if you're not), then simply saying
    char *ptr = malloc(100000000);
    doesn't immediately cause the OS to find 100Mb of memory and hand it over to you. Linux is lazy (re: efficient). Physical memory pages will only be allocated by the VM when you actually touch the memory (say by writing to it).

    The virtual size (VSS) will probably go up, but the resident size (RSS) won't budge until you start using that memory.

    Since you're allocating a lot, the stuff at the beginning of the block will age pretty quickly and may start to be written to swap before you get to touching the blocks at the end of the allocation. This you'll see as RSS levelling off at some point.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  13. #13
    Registered User
    Join Date
    Nov 2015
    Posts
    7
    Quote Originally Posted by Salem View Post
    Assuming you're using Linux (you need to say what if you're not), then simply saying
    char *ptr = malloc(100000000);
    doesn't immediately cause the OS to find 100Mb of memory and hand it over to you. Linux is lazy (re: efficient). Physical memory pages will only be allocated by the VM when you actually touch the memory (say by writing to it).

    The virtual size (VSS) will probably go up, but the resident size (RSS) won't budge until you start using that memory.

    Since you're allocating a lot, the stuff at the beginning of the block will age pretty quickly and may start to be written to swap before you get to touching the blocks at the end of the allocation. This you'll see as RSS levelling off at some point.
    Aha!

    But how would one write to the whole memory block ive allocated?
    Like, is it enought to set the char = "random string"; for it to allocate all of it ?

    thank you

  14. #14
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,110
    memset perhaps.

    Or str[i] for each i on a 4K boundary perhaps.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  15. #15
    Registered User
    Join Date
    Nov 2015
    Posts
    7
    Quote Originally Posted by Salem View Post
    memset perhaps.

    Or str[i] for each i on a 4K boundary perhaps.
    Sir, I love you <3

    *throwing a big kiss

    EDIT: For anyone looking for the answer, It is that I just allocated the memory, and since linux is "lazy " it never actually "makes?" it untill you use memset!
    Last edited by Jozef; 11-24-2015 at 05:29 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Allocating again and again? HELP
    By givmefive5 in forum C Programming
    Replies: 1
    Last Post: 10-12-2011, 03:56 AM
  2. malloc not actually allocating right amount of memory?
    By somerandomdude in forum C Programming
    Replies: 4
    Last Post: 10-02-2011, 12:43 PM
  3. Replies: 7
    Last Post: 05-19-2010, 02:12 AM
  4. allocating memory with malloc
    By steve1_rm in forum C++ Programming
    Replies: 32
    Last Post: 12-18-2008, 06:51 PM
  5. Allocating ram
    By trancedeejay in forum Linux Programming
    Replies: 3
    Last Post: 12-19-2005, 03:58 PM

Tags for this Thread