Thread: Why use malloc()

  1. #16
    Reverse Engineer maxorator's Avatar
    Join Date
    Aug 2005
    Location
    Estonia
    Posts
    2,318
    Elysia demonstrated a char array as a local variable. Only use it as a local variable for small amounts of memory (maybe up to 1 Kbyte).

    I-See-C, the code you posted is way too overcomplicated (and yeah, it's bad code lol).
    Code:
    char word[]={"abcdefghijklmnopqrstuvwxyz"}; //the compiler calculates the length itself here
                                                //(and adds a NULL terminator), don't worry about it
    ptr=malloc(sizeof(word) * sizeof(char));
    if(ptr==NULL){
        printf("err");
    }
    else{
        strcpy(ptr,word); //strcpy copies a whole string, not only one char
        printf("%s\n",ptr); //%s = char* (so yes, no *) 
        free(ptr);
    }
    And this is it!

    Edit: Oops, sizeof and strlen mixed, sorry.
    Last edited by maxorator; 11-26-2007 at 03:21 PM.
    "The Internet treats censorship as damage and routes around it." - John Gilmore

  2. #17
    Registered User
    Join Date
    Nov 2007
    Posts
    8
    Wow, there is a wealth of information here. I tried searching all over the web for information on malloc, and nothing even came close to the great information provided here, not only on malloc, but other lil' parts of C. Thank you everyone, especially maxorator, Elysia, and matsp.

  3. #18
    Registered User
    Join Date
    Nov 2007
    Posts
    8
    Hmm.. Using maxorator's code, I changed the 2nd line to:
    Code:
    ptr = malloc(1);
    I thought this would crash or cause errors, but everything still works perfectly fine. I tried substantially increasing the length of the char array, and it still didn't cause any errors. Why isn't crashing?

  4. #19
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,653
    1) Malloc may allocate enough memory
    2) You "luckily" enough write into process owned memory (but maybe at the cost of overwriting something).
    Don't assume it will crash - sometimes it won't, sometimes it will. Just avoid doing such bad practices because they'll but you in the ass and you'll tear you hair out when you can't find out why later.

  5. #20
    Registered User
    Join Date
    Nov 2007
    Posts
    8
    lol, k.

    And just one finally question:

    If I do:
    Code:
    	char* alpha;
    	
    	alpha = "abcdefghijklmnopqrstuvwxyz";
    	
    	printf("%s", alpha);
    I get the exact same result without having to use malloc, and the code is much simpler. So why do we use malloc?

  6. #21
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by I-See-C View Post
    Also, if I get rid of ptr = malloc(1), the code still works exactly the same. So what the heck??
    Using an uninitialized pointer is kind of like pointing a handgun in the dark and pulling the trigger. You might hit your target. On the other hand, you might hit your grandma.

  7. #22
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,339
    Quote Originally Posted by I-See-C View Post
    So why do we use malloc?
    We use malloc to get more memory! For onesies or twosies, there's not usually a point. For a 50 byte constant string, there's no point there either. Think on a bigger and more dynamic scale.

    Let's say you have to read a 20MB file into memory and parse through it a few times. Do you really want to reserve 20MB in your program to do this? If you did, your .exe file is 20MB large, plus the size of your code, with might be 1K. (1,000 bytes, roughly).

    Look at it this way. If your buddies wanted to download your program, it would be a 20.001MB download. However, if you used malloc() on your program, it would be a 1K download.

    Todd

  8. #23
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,653
    Quote Originally Posted by I-See-C View Post
    lol, k.

    And just one finally question:

    If I do:
    Code:
    	char* alpha;
    	
    	alpha = "abcdefghijklmnopqrstuvwxyz";
    	
    	printf("%s", alpha);
    I get the exact same result without having to use malloc, and the code is much simpler. So why do we use malloc?
    Yes, this is fine because the compiler will put that string, usually in the data segment and assign the address of that string to your pointer. So that's fine.
    However, the compiler usually puts it in a read-only segment, so what happens when you need to modify that string? Access violation! Crash! So, you need to allocate it on the stack or the heap.

    Quote Originally Posted by brewbuck View Post
    Using an uninitialized pointer is kind of like pointing a handgun in the dark and pulling the trigger. You might hit your target. On the other hand, you might hit your grandma.
    LOL.
    Nice analogy!

    Quote Originally Posted by Todd Burch View Post
    We use malloc to get more memory! For onesies or twosies, there's not usually a point. For a 50 byte constant string, there's no point there either. Think on a bigger and more dynamic scale.

    Let's say you have to read a 20MB file into memory and parse through it a few times. Do you really want to reserve 20MB in your program to do this? If you did, your .exe file is 20MB large, plus the size of your code, with might be 1K. (1,000 bytes, roughly).

    Look at it this way. If your buddies wanted to download your program, it would be a 20.001MB download. However, if you used malloc() on your program, it would be a 1K download.

    Todd
    Another catch: if you don't use malloc, you're limited to the size of the stack, which usually is around 1 MB (default on Windows). So if you use more than one MB of memory... uhoh! You need to allocate on the heap (in the computer RAM), which is exactly what malloc does!

    And another reason is, as mentioned, dynamically allocating memory - allocating when you need some memory for something, whatever that may be.

  9. #24
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Quote Originally Posted by I-See-C View Post
    So why do we use malloc?
    Read my post and don't post again until you've read it.

  10. #25
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by Todd Burch View Post
    We use malloc to get more memory! For onesies or twosies, there's not usually a point. For a 50 byte constant string, there's no point there either. Think on a bigger and more dynamic scale.

    Let's say you have to read a 20MB file into memory and parse through it a few times. Do you really want to reserve 20MB in your program to do this? If you did, your .exe file is 20MB large, plus the size of your code, with might be 1K. (1,000 bytes, roughly).
    [pedant]
    Actually, unless you also initialize the memory, it will take no space at all [as there is already a field saying "how big is the un-initialized data section", and it doesn't matter if that field is 0x38, 0x1438 or 0x1400038 - it's a 32-bit value anyways ]. And the stdio package and such probably come to a few kilobytes when you link it in.
    [/pedant]

    But I agree with the concept of "think big" or "think unknown". If you know how much you could possibly expect, then a staticly sized array is most often the right solution. When you need LOTS of memory, or you need a highly variable number of "things", then malloc is the right solution. If you need "at most 100", then it's fine to use a fixed size array. If you don't know if you need 15 or 150000, then use dynamic memory in some form. There is of course no hard and fast rules, and the amount of memory you "may want to use as a static array" can vary greatly from system to system - a small embedded system may not be the ideal place to put a 15 * 100 array as a local variable [as that is 1500 bytes, and the stack may be only 2KB in total size, for example] - but on a desktop PC, that's not a big deal at all - the stack can grow to megabytes, and 1500 bytes is nothing in this case.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  11. #26
    Registered User
    Join Date
    Nov 2007
    Posts
    8
    Thanks for the clarifications. And MacGyver, I previously read your post but it didn't cover all the bases. Just because you think your single explanation seems to be the utmost best at answering everything, doesn't mean it truly is. Remember, I'm not you.

  12. #27
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by Elysia View Post
    Another catch: if you don't use malloc, you're limited to the size of the stack, which usually is around 1 MB (default on Windows). So if you use more than one MB of memory... uhoh! You need to allocate on the heap (in the computer RAM), which is exactly what malloc does!
    The stack comments only apply to local automatic variables - you can use as much memory as you like in global variables or local static variables. There are of course all sorts of good reasons NOT to use global variables, but if for example what you are doing is to process a large image-file, and you wish to just read 16 MB of image-file into memory, then you can do that into a global variable - no problem from that perspective [you may need to THINK about what you are doing to it in terms of processing, but that applies if you pass a pointer to some 16MB around too - it's essentially no difference, except your pointer may be a local variable in main or "doProcessing" or some such].

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  13. #28
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Quote Originally Posted by I-See-C View Post
    Thanks for the clarifications. And MacGyver, I previously read your post but it didn't cover all the bases. Just because you think your single explanation seems to be the utmost best at answering everything, doesn't mean it truly is. Remember, I'm not you.
    I don't think my explanation was the only one or the best. I just get irritated with people asking the same questions that other people have answered.

    We have the same questions asked repeatedly. More than once per thread... well, yeah. It gives the appearance you're not even reading anything we're writing.
    Last edited by MacGyver; 11-26-2007 at 05:36 PM.

  14. #29
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by I-See-C View Post
    lol, k.

    And just one finally question:

    If I do:
    Code:
    	char* alpha;
    	
    	alpha = "abcdefghijklmnopqrstuvwxyz";
    	
    	printf("%s", alpha);
    I get the exact same result without having to use malloc, and the code is much simpler. So why do we use malloc?
    Because Lets say you wanted to change the first letter alpha points to to an 'A' (uppercase instead of lowercase). That will likely crash as you'd be trying to modify memory that's part of your applications static data segment.
    If you malloc a copy first, then you can do whatever you want to the copy.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  15. #30
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,653
    Quote Originally Posted by matsp View Post
    The stack comments only apply to local automatic variables - you can use as much memory as you like in global variables or local static variables. There are of course all sorts of good reasons NOT to use global variables, but if for example what you are doing is to process a large image-file, and you wish to just read 16 MB of image-file into memory, then you can do that into a global variable - no problem from that perspective [you may need to THINK about what you are doing to it in terms of processing, but that applies if you pass a pointer to some 16MB around too - it's essentially no difference, except your pointer may be a local variable in main or "doProcessing" or some such].

    --
    Mats
    But global variables aren't put on the stack, are they? They're put in a special section if I'm not mistaken.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc + segmentation fault
    By ch4 in forum C Programming
    Replies: 5
    Last Post: 04-07-2009, 03:46 PM
  2. the basics of malloc
    By nakedBallerina in forum C Programming
    Replies: 21
    Last Post: 05-20-2008, 02:32 AM
  3. Is there a limit on the number of malloc calls ?
    By krissy in forum Windows Programming
    Replies: 3
    Last Post: 03-19-2006, 12:26 PM
  4. Malloc and calloc problem!!
    By xxhimanshu in forum C Programming
    Replies: 19
    Last Post: 08-10-2005, 05:37 AM
  5. malloc() & address allocation
    By santechz in forum C Programming
    Replies: 6
    Last Post: 03-21-2005, 09:08 AM