Thread: Memory Functions - Still Learning

  1. #1
    Odd Mental Process Alexander's Avatar
    Join Date
    Aug 2008
    Posts
    22

    Memory Functions - Still Learning

    I just don't get these at all:
    malloc()
    free()
    realloc()
    calloc()

    I think I'm having a hard time grasping the point in what these are for.

    I'm reading this tutorial by beej. Here.
    And I don't quite get why I want these functions. Doesn't it already do all of this automatically or something? I'm totally just lost on this. I barely made it past the different variable types like int, long int, and short int, and I still barely understand why those matter. I need why I need these explained to me. D:

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    There are three areas of memory that a C program can make use of:
    Data - where global variables live.
    Stack - where your local variables in functions live.
    Heap - data that is not assigned to any specific purpose. Often called "dynamic memory", because it is able to adjust to the situations of the application.

    For many purposes, global and local variables are sufficient to solve any particular problem. However, sometimes we find ourselves in a position where we can't determine beforehand how much space should be used for something - for example, a text-editor (such as notepad) can decide to store data in a 2D array
    Code:
    char text[NUMLINES][CHARSPERLINE];
    However, this isn't very flexible - we would have to have a HUGE number in NUMLINES, and CHARSPERLINE would also have to be large to prevent it from falling over if there are long lines in the file. [And even so, we would be using a huge amount of memory, and that's pretty meaningless for a small file [1]]

    So, to solve these problems, we store data in the heap instead of as a global or local variable. This way, we don't have to decide when we WRITE the application how much space we need for something, but we can ask for the amount of memory we need when we know how much we need.

    There are also alternatives to storing data in arrays, for example we have binary trees or linked lists, where the data is stored with "links" from one element to the next. This makes it very easy to add new elements (and in the case of a binary tree, it is sorted in some sort of order, so we can find things very quickly (log2(n) steps at most - so a tree with 1000 items would only need to search 10 items to find the one you are looking for).

    malloc is the basic function to ask the system to get a chunk of memory of x bytes.
    calloc is almost identical to malloc - it takes two parameters, a size of each element and a number of elements. Aside from that, it also clears the memory to zero - which is handy at times.
    realloc "grows" the memory from a previous allocation - so if you have allocated some number of items, and find that it wasn't big enough, calling realloc will give you some more space. You can also reduce the size of a chunk of memory with realloc, but it's less often used that way.
    free returns the memory you requested in any of the above functions. It is important in an application to free all the memory you allocated [2].

    [1] Yes, I know, the OS won't (or at least may not) actually commit real memory to the whole chunk of memory "text" in this case.

    [2] Some argue that it isn't - but like when we study physics at the beginners level, we ignore the Relativity theory - let's start with a simple view by assuming that all memory should be freed.

    --
    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.

  3. #3
    Malum in se abachler's Avatar
    Join Date
    Apr 2007
    Posts
    3,195
    Quote Originally Posted by Alexander View Post
    I just don't get these at all:
    malloc()
    free()
    realloc()
    calloc()
    Code:
    char* Pointer = malloc(512);
    Pointer now points to a 512 byte area of memory that was allocated (on the heap)

    Code:
    Pointer = realloc(Pointer , 1024);
    Pointer now points to a 1024 byte area of memory. This area may have the sem base address or it may be different. If the address changes, the contents of the previous memory are copied intot eh new location and the previous heap object is freed.
    Code:
    free(Pointer);
    Pointer is no longer valid (although it still points to the area of memory). Attempting to write to the area of memory will cause a general protection fault. The memory is now available for other threads to allocate it.

    calloc() is similar to maloc, excpt it lets you specifiy the element size and count of the array you are allocating. All it does is multiply the two numbers and then execute a malloc().

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by abachler View Post
    [code]
    calloc() is similar to maloc, excpt it lets you specifiy the element size and count of the array you are allocating. All it does is multiply the two numbers and then execute a malloc().
    And zero it. You can easily simulate calloc this way:
    Code:
    void *calloc(size_t nmemb, size_t size)
    {
       void *p = malloc(nmemb * size);
       if (p)
          memset(p, nmemb * size, 0);
       return p;
    }
    --
    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.

  5. #5
    Technical Lead QuantumPete's Avatar
    Join Date
    Aug 2007
    Location
    London, UK
    Posts
    894
    Quote Originally Posted by matsp View Post
    Code:
    memset(p, nmemb * size, 0);
    I think you mean:
    Code:
    memset (p, 0, nmemb * size);
    QuantumPete
    "No-one else has reported this problem, you're either crazy or a liar" - Dogbert Technical Support
    "Have you tried turning it off and on again?" - The IT Crowd

  6. #6
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by QuantumPete View Post
    I think you mean:
    Code:
    memset (p, 0, nmemb * size);
    QuantumPete
    Doh! Yes, of course. I ALWAYS confuse the arguments of memset. So I looked it up, but I still got it wrong!

    --
    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.

  7. #7
    Registered User Dogmasur's Avatar
    Join Date
    Jul 2008
    Posts
    72
    Isn't it also true that malloc always returns a character pointer, so in order to have it allocate another type it would need to be typecast? I just started learning about malloc myself and am trying to get a better grip on it.
    "The art of living is more like wrestling than dancing." - Marcus Aurelius

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Isn't it also true that malloc always returns a character pointer, so in order to have it allocate another type it would need to be typecast?
    No, malloc() returns a void*.
    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
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by laserlight View Post
    No, malloc() returns a void*.
    At least in compilers that follow the ANSI C89/ISO C90 standards - so any compiler produced in the last 15 or so years, that would be. Pre-ANSI, I think malloc would actually returned char * - but if you are using a C-library that has that old of a definition, it's certainly time to get a newer one.

    --
    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.

  10. #10
    Registered User Dogmasur's Avatar
    Join Date
    Jul 2008
    Posts
    72
    I'm using a current compiler, but was reading out of an older book. Thanks for the heads up.
    "The art of living is more like wrestling than dancing." - Marcus Aurelius

  11. #11
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by Dogmasur View Post
    I'm using a current compiler, but was reading out of an older book. Thanks for the heads up.
    Probably should get a newer book then ...

    --
    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.

  12. #12
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300

    Exclamation

    "Doesn't it already do all of this automatically or something? "

    Not only does it not get done automatically, but you when you do it you need to make sure it gets done right. For example, if you have a character *pointer which you want to refer to a string, you get the length of the string, MemoryALLOCate it enough storage, then copy the string in:
    Code:
    #include <string.h>
    #include <stdlib.h>
    
    int main() {
            char *string;
            size_t len;
            len = strlen("a string");
            string=malloc(len+1);
            strcpy(string, "a string");
            puts(string);
    }
    But if there isn't enough memory, malloc will return a NULL pointer and you will get a segfault.
    So always check by inserting something like this:
    Code:
    string=malloc(len+1);
    if (string==NULL) puts("malloc error!");
    You should actually just kill the program in that case, so to save yourself some time create an "error-checked malloc" function and use it instead of malloc:
    Code:
    void *ec_malloc (unsigned int bytes) {
    	void *assign;  
    	assign = malloc(bytes);		
    	if (assign == NULL) exit(-1);
    	return assign;
    }
    So now in main you can go:
    string=ec_malloc(len+1);
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  13. #13
    Odd Mental Process Alexander's Avatar
    Join Date
    Aug 2008
    Posts
    22
    Ok, I'm still confused. How do I know when I need to use these functions? Is there any sort of output that will allow me to see what these are doing and such.

    Sorry. I'm often a visual learner, so I'm having a hard time grasping this. -.-;

  14. #14
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Quote Originally Posted by Alexander View Post
    Ok, I'm still confused. How do I know when I need to use these functions?
    Whenever you ask yourself "How many of these do I need?" and your answer is "I don't know."

  15. #15
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    If you know you need exactly 5 ints, you can do this:
    Code:
    int nums[5];
    but if you don't know how many ints you need until you actually run the program, you need to allocate enough space at runtime:
    Code:
    int* nums = malloc( size * sizeof(int) );

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 02-06-2009, 12:27 PM
  2. Reallocating Memory
    By Booie2k1 in forum C Programming
    Replies: 3
    Last Post: 03-11-2008, 06:09 AM
  3. Locating A Segmentation Fault
    By Stack Overflow in forum C Programming
    Replies: 12
    Last Post: 12-14-2004, 01:33 PM
  4. Accessing Video Memory Information...need help
    By KneeLess in forum C++ Programming
    Replies: 8
    Last Post: 08-24-2003, 03:53 PM
  5. Manipulating the Windows Clipboard
    By Johno in forum Windows Programming
    Replies: 2
    Last Post: 10-01-2002, 09:37 AM

Tags for this Thread