什么是C语言中的malloc函数?

该malloc()函数代表内存分配,即动态分配一个内存块。

它为指定的大小保留内存空间,并返回空指针,该指针指向内存位置。

malloc()函数带有垃圾值。返回的指针的类型为void。

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,"nhooo");
   }
   printf("Dynamically allocated memory content : %s\n", MemoryAlloc);
   free(MemoryAlloc);
}
输出结果

执行以上程序后,将产生以下结果-

Dynamically allocated memory content: nhooo