ฟังก์ชัน malloc() หมายถึงการจัดสรรหน่วยความจำ ซึ่งจัดสรรบล็อกของหน่วยความจำแบบไดนามิก
มันสงวนพื้นที่หน่วยความจำสำหรับขนาดที่ระบุและส่งคืนตัวชี้ null ซึ่งชี้ไปยังตำแหน่งหน่วยความจำ
ฟังก์ชัน malloc() มีค่าขยะ ตัวชี้ที่ส่งคืนเป็นประเภทเป็นโมฆะ
ไวยากรณ์สำหรับฟังก์ชัน malloc() มีดังนี้ -
ptr = (castType*) malloc(size);
ตัวอย่าง
ตัวอย่างต่อไปนี้แสดงการใช้งานฟังก์ชัน malloc()
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(){
char *MemoryAlloc;
/* memory allocated dynamically */
MemoryAlloc = malloc( 15 * sizeof(char) );
if(MemoryAlloc== NULL ){
printf("Couldn't able to allocate requested memory\n");
}else{
strcpy( MemoryAlloc,"TutorialsPoint");
}
printf("Dynamically allocated memory content : %s\n", MemoryAlloc);
free(MemoryAlloc);
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
Dynamically allocated memory content: TutorialsPoint