#include <stdlib.h>
void *malloc( size_t size );
函数指向一个大小为 size 的空间,如果发生错误,则返回 NULL。存储空间的指针必须为堆,不能是栈。这样以便以后用 free 函数释放空间。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <process.h>
int main(void)
{
char *str;
/* allocate memory for string */
/* This will generate an error when compiling */
/* with C++, use the new operator instead. */
if ((str = malloc(10)) == NULL)
{
printf("Not enough memory to allocate buffer\n");
exit(1); /* terminate program if out of memory */
}
/* copy "Hello" into string */
strcpy(str, "Hello");
/* display string */
printf("String is %s\n", str);
/* free memory */
free(str);
return 0;
}输出结果:
String is Hello