C++中的malloc函数(详细指南)

1,062 阅读2分钟

malloc是一个C++库函数,它分配所请求的内存并返回一个指针。这被称为动态内存分配,允许在移动中分配内存。它的前身是用于内存分配的c++new操作符。

要分配的字节数被作为单一参数传递。成功时,该函数会返回一个指向所分配内存的起始点的指针,失败时则返回一个空指针。

malloc

语法

void *malloc (size_t size)

返回类型是一个指向所分配内存的起始点的指针。或在失败时返回空指针
参数
是要分配的字节数

注意事项

指针使用完毕后,通过传递返回的指针调用free()函数。这样就可以取消分配的内存部分,避免内存泄漏。

例子

#include <stdio.h>
#include <stdlib.h>

int main(){
	
	char *str;
	
//call malloc and cast to string before adding "Man The Guns!" to 'str'
	str = (char *) malloc(15);
	strcpy(str, "Man The Guns!");
	printf("String = %s, Address = %u\n",str,str);
	
//to increase the size of string realloc is used. We now add string ". Now What?" to the string. 
	str =(char *)realloc(str,25);
	strcat(str," Now What?");
	printf("String = %s, Address=%u\n",str,str);
	
	//Finally, we call free up the memory allocated by calling 'free()'
	free(str);
	
	return 0;
}

malloc, free and realloc

Malloc函数与*free()realloc()*一起使用,用于处理安全的动态内存分配。尽管在现代C++应用程序中,推荐使用new和delete操作符。

使用new而不是malloc()的原因

  1. 错误处理,因为malloc()并不抛出错误。你需要检查是否为空值

  2. malloc()不是类型安全的,如果你看一下示例代码,你会发现我们需要对返回的值进行转换以获得可用的数据。

  3. malloc()不是面向对象的。因此,在你的C++代码中混合使用malloc()new会使它容易出错。

只有少数情况需要使用malloc()来替代new操作。比如重新分配数据大小,而new操作符无法做到。

问题

#include <stdio.h>
#include <stdlib.h>

int main(){
	
	char *str;
	
	str = (char *) malloc(15);
	strcpy(str, "Man The Guns!");
	printf("String = %s, Address = %u\n",str,str);
	free(str);
	
	str =(char *)malloc(5);
	strcpy(str," What?");
	printf("String = %s, Address=%u\n",str,str);
	free(str);
	
	return 0;
}
  1. 字符串=输出是什么?
  2. 地址会是相同的值吗?

通过OpenGenus的这篇文章,你一定对C++中的malloc()有了一定的了解。