Definition | #include <stdlib.h> void *malloc(size_t n);
| |
Return val. | Pointer to the new memory area | |
provided | ||
NULL pointer | if | |
Notes | The new data area begins on a double word boundary. The actual length of the data area amounts to: If You should use the A serious disruption in working memory may be expected if the length of the memory area If n has the value 0, | |
Example 1 | The following program fragment requests memory space for 30 integer elements. #include <stdlib.h> int *int_array; . . . int_array = (int *)malloc(30 * sizeof(int)); |
Example 2 | Dynamic reservation of memory space for data on second-hand cars: #include <stdio.h> #include <stdlib.h> #define MAX 20; struct car { char *type; int age; long kilometers; char inspect[6]; int cond; int price; struct car *n; } *list; int main(void) { int mark; if((list = (struct car *)malloc(sizeof(*list))) == NULL) { printf("Memory space exhausted\n"); exit(1); } /* N.B. !! The preceding malloc call only provided space for a pointer */ /* (4 bytes) for the member type. Space for the type identifier must still */ /* be provided. */ if((list->type = (char *)calloc(1,20)) == NULL) exit(1); /* error */ /* Input used car */ scanf("%20s %d", list->type, &list->age); scanf("%d %6s %d %d", &list->kilometers, list->inspect, &list->cond, &list->price); list->n = NULL; /* print input values */ printf("%s\n%d\n", list->type, list->age); printf("%d\n%.6s\n%d\n%d", list->kilometers, list->inspect, list->cond, list->price); /* free memory space */ free(list); return 0; } |
See also | calloc, realloc, free, garbcoll, memalloc, memfree |