EmbLogic's Blog

E10 pointers

I dint understand the concept of malloc Function..?

One Response to E10 pointers

  1. varun.singh says:

    malloc (memory allocation) is used to dynamically allocate memory from the heap at run time.
    eg.
    The simplest way to reserve memory is to code something like:
    main()
    {
    char string[1000];

    strcpy (string, “some text”);
    }
    The example above has two problems:

    If the data is less than 1000 bytes we are wasting memory.
    If the data is greater than 1000 bytes the program is going to crash.
    The 1000 bytes are reserved throught out the life of the program. If this was a long running program that rarely used the memory, it would again be wasteful.
    so we use malloc()
    malloc allows us to allocate exactly the correct amount of memory

    Library: stdlib.h
    Prototype: void *malloc(size_t size);
    Syntax: char * String;
    String = (char *) malloc(1000);

    Looking at the example syntax above, 1000 bytes are reserved and the pointer String points to the first byte. The 1000 bytes are NOT initialized by malloc. If the memory is NOT available, a NULL pointer is returned.
    the cast is required to return a pointer of the correct type.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>