
Lập chương trình cho
máy tính
CẤP PHÁT BỘ NHỚ ĐỘNG
Học kỳ 2, 2004-2005

Lập trình C - CNTT2. 2002 - 2005 132
Cấp phát động: malloc() và
calloc()
Hàm malloc và calloc cho phép cấp phát các vùng nhớ ngay
trong lúc chạy chương trình.
void *malloc( size_t size);
void *calloc( size_t nItems, size_t size);
Hàm calloc cấp phát vùng nhớ và khởi tạo tất cả các bit trong
vùng nhớ mới cấp phát về 0.
Hàm malloc chỉ cấp phát vùng nhớ.

Lập trình C - CNTT2. 2002 - 2005 133
Ví dụ 1: dùng malloc()
1. #include <stdio.h>
2. #include <string.h>
3. #include <alloc.h>
4. #include <process.h>
5. int main(void)
6. { char *str;
7. /* allocate memory for string */
8. if ((str = (char *) malloc(10)) == NULL)
9. {
10. printf("Not enough memory to allocate buffer\n");
11. exit(1); /* terminate program if out of memory */
12. }

Lập trình C - CNTT2. 2002 - 2005 134
Ví dụ 1: (tt)
13. /* copy "Hello" into string */
14. strcpy(str, "Hello");
15. /* display string */
16. printf("String is %s\n", str);
17. /* free memory */
18. free(str);
19. return 0;
20. }

Lập trình C - CNTT2. 2002 - 2005 135
Ví dụ 2: calloc()
1. #include <stdio.h>
2. #include <alloc.h>
3. #include <string.h>
4. int main(void)
5. {
6. char *str = NULL;
7. /* allocate memory for string */
8. str = (char *) calloc(10, sizeof(char));
9. /* copy "Hello" into string */
10. strcpy(str, "Hello");

