Wednesday, February 24, 2010

C - malloc Function definition


 

 

malloc

malloc requires one argument - the number of bytes you want to allocate dynamically.
If the memory allocation was successful, malloc will return a void pointer - you can assign this to a pointer variable, which will store the address of the allocated memory.
If memory allocation failed (for example, if you're out of memory), malloc will return a NULL pointer.
Passing the pointer into free will release the allocated memory - it is good practice to free memory when you've finished with it.
This example will ask you how many integers you'd like to store in an array. It'll then allocate the memory dynamically using malloc and store a certain number of integers, print them out, then releases the used memory using free.
#include 
#include  /* required for the malloc and free functions */

int main() {
  int number;
  int *ptr;
  int i;

  printf("How many ints would you like store? ");
  scanf("%d", &number);

  ptr = malloc(number*sizeof(int)); /* allocate memory */
 
  if(ptr!=NULL) {
    for(i=0 ; i
      *(ptr+i) = i;
    }

    for(i=number ; i>0 ; i--) {
      printf("%d\n", *(ptr+(i-1))); /* print out in reverse order */
    }

    free(ptr); /* free allocated memory */
    return 0;
  }
  else {
    printf("\nMemory allocation failed - not enough memory.\n");
    return 1;
  }
}
Output if I entered 3:
How many ints would you like store? 3
2
1
0
When I first wrote the example using a Borland compiler, I had to cast the returned pointer like this:
ptr = (int *)malloc(number*sizeof(int));
The above example was tested in MSVC++ but try casting the pointer if your compiler displays an error.



No comments:

Post a Comment