本章介绍C语言中的动态内存管理。C编程语言提供了几种用于内存分配和管理的函数。 这些函数可以在<stdlib.h>头文件中找到。
Sr.No. | Function & 描述 |
---|---|
1 | void* calloc(int num,int size); 此函数分配一个 num 个元素的数组,每个元素的字节大小将为 size 。 |
2 | void free(void * address); 该函数释放由地址指定的存储块。 链接:https://www.learnfk.comhttps://www.learnfk.com/c-programming/c-memory-management.html 来源:LearnFk无涯教程网 |
3 | void* malloc(int num); 此函数分配一个 num 个字节的数组,并使它们未初始化。 |
4 | void * realloc(void * address,int newsize); 此函数重新分配内存,将其扩展到 newsize 。 |
在编程时,如果您知道数组的大小,那么这很容易,您可以将其定义为数组。如,要存储任何人的名字,最多可以包含100个字符,因此您可以定义以下内容-
char name[100];
但是,现在让我们考虑一种情况,您对所需存储的文本长度一无所知。在这里,我们需要定义一个指向字符的指针,而无需定义需要多少内存,稍后,根据需求,我们可以分配内存,如下示例所示:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char name[100]; char *description; strcpy(name, "Learnfk.com"); /* 动态分配内存 */ description=malloc( 200 * sizeof(char) ); if( description == NULL ) { fprintf(stderr, "Error - unable to allocate required memory\n"); } else { strcpy( description, "Learnfk.com a DPS student in class 10th"); } printf("Name=%s\n", name ); printf("Remark: %s\n", description ); }
编译并执行上述代码后,将产生以下输出。
Name = Learnfk.com Remark: Learnfk.com a DPS student in class 10th
可以使用 calloc(); 编写相同的程序,唯一的事情是您需要用calloc替换malloc,如下所示:
calloc(200, sizeof(char));
因此,您拥有完全的控制权,并且可以在分配内存时传递任何大小值,这与数组中定义的大小无法更改的数组不同。
当您的程序发布时,操作系统会自动释放程序分配的所有内存,但是作为一种好的做法,当您不再需要内存时,应该通过调用函数 free()。
另外,您可以通过调用函数 realloc()来增加或减少分配的内存块的大小。让我们再次检查以上程序,并使用realloc()和free()函数-
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char name[100]; char *description; strcpy(name, "Toolfk.com"); /* 动态分配内存 */ description=malloc( 30 * sizeof(char) ); if( description == NULL ) { fprintf(stderr, "Error - unable to allocate required memory\n"); } else { strcpy( description, "Toolfk.com a DPS student."); } /* 假设您想存储更大的描述 */ description=realloc( description, 100 * sizeof(char) ); if( description == NULL ) { fprintf(stderr, "Error - unable to allocate required memory\n"); } else { strcat( description, "She is in class 10th"); } printf("Name=%s\n", name ); printf("Remark: %s\n", description ); /* 使用 free() 函数释放内存 */ free(description); }
编译并执行上述代码后,将产生以下输出。
Name = Toolfk.com Remark: Toolfk.com a DPS student in class 10th
您可以尝试上面的示例,而无需重新分配额外的内存,由于说明中缺少可用内存,strcat()函数将给出错误。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)