Dynamic Memory Allocation :: malloc(3), calloc(3), bzero(3), memset(3)

Dynamic Memory Allocation :: malloc(3), calloc(3), bzero(3), memset(3)

  • The prototype for malloc(3) is:
      void *malloc(size_t size);
    malloc takes in a size_t and returns a void pointer. Why does it return a void pointer? Because it doesn't matter to malloc to what type this memory will be used for.
  • Let's see an example of how malloc is used:
      int *ip;

    ip = malloc(5 * sizeof(int));
    /* .. OR .. */
    ip = malloc(5 * sizeof(ip));
    Pretty simplistic. sizeof(int) returns the sizeof an integer on the machine, multiply by 5 and malloc that many bytes. The second malloc works because it sends what ip is pointing to, which is an int.
  • Wait... we're forgetting something. AH! We didn't check for return values. Here's some modified code:
      #define INITIAL_ARRAY_SIZE 5
    /* ... code ... */
    int *ip;

    if ((ip = malloc(INITIAL_ARRAY_SIZE * sizeof(int))) == NULL) {
    (void)fprintf(stderr, "ERROR: Malloc failed");
    (void)exit(EXIT_FAILURE); /* or return EXIT_FAILURE; */
    }
    Now our program properly prints an error message and exits gracefully if malloc fails.
  • calloc(3) works like malloc, but initializes the memory to zero if possible. The prototype is:
      void *calloc(size_t nmemb, size_t size);
    Refer to Weiss pg. 164 for more information on calloc.
  • bzero(3) fills the first n bytes of the pointer to zero. Prototype:
      void bzero(void *s, size_t n);
    If you need to set the value to some other value (or just as a general alternative to bzero), you can use memset:
      void *memset(void *s, int c, size_t n);
    where you can specify c as the value to fill for n bytes of pointer s.

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post