动态内存的传递

xiaoxiao2021-02-27  215

先看如下一段代码:

#include <iostream> using namespace std ; void Getmemory(char* p ,int num) { p = (char*)malloc(sizeof(char)*num) ; } int main() { char *str = NULL ; Getmemory(str,10) ; strcpy(str,"hello") ; return 0 ; }         上述代码中,Getmemory函数是有问题的,Getmemory函数体内的p实际上是main函数中的str变量在Getmemory函数栈中的一个备份,因为编译器总是为函数的每个参数制作临时的变量。因此虽然在代码第6行中p申请了堆内存,但是返回到main函数时,str还是Null,并不指向那块内存,所以代码第14行调用strcpy时会导致程序崩溃。

        实际上,Getmemory并不能做任何有用的事情,这里还要注意,由于从Getmemory函数返回时不能获得堆中内存的地址,那块堆内存就不能被继续引用,也就得不到释放,因此调用一次Getmemory函数就会产生num字节的内存泄漏。

可以试着先分析下面两个代码段的输出(动态内存的传递)

程序1:

char * Getmemory() { char p[] = "hello world" ; return p ; } void test(void) { char *str = NULL ; str = Getmemory() ; printf(str) ; }

程序2:

void Getmemory(char *p) { p = (char *)malloc(100) ; } void test(void) { char *str = NULL ; Getmemory(str) ; strcpy(str,"hello world") ; printf(str) ; }        程序1的Getmemory()返回的是指向栈内存的指针,该指针的地址不是NULL,但是当栈退出后,内容不定,有可能会输出乱码。

      程序2的Getmemory()没有返回值,这个函数不能传递动态内存。在test函数中,str变量的值通过参数传值得方式赋给Getmemory()的局部变量p。但是test()中的str一直未NULL,所以第10行中的调用会使程序崩溃。此外,由于堆内存在Getmemory()执行之后没有指针引用它,因此会产生内存泄漏。

转载请注明原文地址: https://www.6miu.com/read-8856.html

最新回复(0)