简体   繁体   English

如果您不释放函数中动态分配的内存会怎样?

[英]What happens if you don't free dynamically allocated memory in a function?

I am learning how to write functions in C to accept an array and return a modified array. 我正在学习如何在C语言中编写函数以接受数组并返回修改后的数组。

In function testfunc (which is supposed to simply add 10 to each element of input array b ) I am allocating memory for npts number of integers using malloc . 在函数testfunc (应该简单地将10添加到输入数组b每个元素中)中,我正在使用mallocnpts个整数分配内存。 But since I want to return this array using a pointer, I am not freeing this memory at the end of the function. 但是由于我想使用指针返回此数组,所以我没有在函数末尾释放此内存。 Suppose I call this function 100 times like I am doing in the code, so what happens to the all the memory allocated during the code ? 假设我像在代码中一样调用此函数100次,那么在代码期间分配的所有内存又会如何? Is the amount of memory used by the code 100*10*4 bytes ? 代码使用的内存量是100*10*4字节吗? For a function which doesn't work on dynamic memory allocation, I think memory allocated to variables disappears when the function returns the final value and when it is called again, it again allocates memory and so on. 对于在动态内存分配上不起作用的函数,我认为分配给变量的内存会在该函数返回最终值时消失,并且在再次调用该函数时,它将再次分配内存,依此类推。 But I am confused as to what happens in this case. 但是我对这种情况下发生的事情感到困惑。

i cannot free the allocated memory inside the function since i need it to return the array to the main function, but also i need to call this function more than 100 times for different arrays, so if it keeps on allocating again and again, it will run out of memory 我无法释放函数内部分配的内存,因为我需要它将数组返回到主函数,但是我还需要为不同的数组调用此函数100次以上,因此,如果它不断反复分配,它将内存不足

And is there a way to check how much memory a code is using ? 有没有一种方法可以检查代码正在使用多少内存? (other than looking at Activity Monitor on Mac-OSX). (而不是在Mac-OSX上查看“活动监视器”)。

Thanks ! 谢谢 !

/* code to test returning array from functions */

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

int* testfunc(int *a,int npts);

int main(int argc, char* argv[])
{
    int *b;
    int a[10],i,j,npts=10;

    b=(int *) malloc(sizeof(int)*npts);

    for (j=0; j <100; j++)
    {
        printf("iteration number %d \n",j);
        for (i=0; i<npts; i++)
        {
            a[i]=i;
            printf("%d \n",a[i]);
        }

        b=testfunc(a,npts);

        printf("returned array \n");
        for (i=0; i<npts; i++)
        {
            printf("%d \n",b[i]);
        }
    }
    printf("the size of one integer is %d \n",sizeof(int));

    return 0;
}
int* testfunc(int *b,int npts)
{
    int *c;
    int i=0;

    c=(int *) malloc(sizeof(int)*npts);

    for (i=0; i<npts; i++)
    {
        c[i]=b[i]+10;
    }

    return c;
}

This is the possible solution to avoid allocating memory inside a function and being able to call the function multiple times 这是避免在函数内部分配内存并能够多次调用该函数的可能解决方案

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

void testfunc(int *c,int *d,int npts);

int main(int argc, char* argv[])
{
    int *a,*b;
    int i,j,npts=10;

    a=malloc(sizeof(int)*npts);
    b=malloc(sizeof(int)*npts);

    for (j=0; j <100; j++)
    {
        printf("iteration number %d \n",j);
        for (i=0; i<npts; i++)
        {
            a[i]=i;
            printf("%d \n",a[i]);
        }

        testfunc(a,b,npts);

        printf("returned array \n");
        for (i=0; i<npts; i++)
        {
            printf("%d \n",b[i]);
        }
    }
    printf("the size of one integer is %d \n",sizeof(int));

    free(a);
    free(b);

    return 0;
}
void testfunc(int *c,int *d,int npts)
{
    int i=0;

    for (i=0; i<npts; i++)
    {
        d[i]=c[i]+10;
    }
}
c=(int *) malloc(sizeof(int)*npts);
:
return c;

This passes back both the memory and the responsibility for managing it. 这样既可以传回内存, 可以管理内存。

It has become the responsibility of the caller ( main in this cae) to free it when finished. 完成后释放它已成为调用者(此cae中的main )的责任。

Where your real problem lies is here in main : 您真正的问题所在在main

b=(int *) malloc(sizeof(int)*npts);
:
for (some number of iterations)
    b=testfunc(a,npts);  // overwrites b

On that "overwrites" line, you actually have a memory leak because you lose access to the memory currently allocated for b (both originally and in the prior iteration of the loop). 在该“覆盖”行上,实际上是发生了内存泄漏,因为您无法访问当前为b分配的内存(无论是原始的还是在循环的先前迭代中)。


And, as an aside, please don't cast the return value of malloc in C. It's not needed and can hide certain subtle errors that you really don't want to have to debug :-) 而且,顺便说一句,请不要投的返回值malloc在C.这是没有必要的,可以隐藏你真的希望有调试:-)某些细微的错误

Since you are using malloc , which means you are allocating memory from heap not stack . 由于您正在使用malloc ,这意味着您是从而不是堆栈中分配内存。
You should firstly figure out the mechanism of heap and stack.In C, malloc will help programmer allocate memory from heap, the same as new in C++. 首先应该弄清楚堆和栈的机制。在C语言中, malloc将帮助程序员从堆中分配内存,这与C ++中的新功能相同。
So even if the function return the final value, the memory allocated will not be freed.If you call the function 100 times, it will allocate memory for you 100 times. 因此,即使函数返回最终值,分配的内存也不会被释放,如果您调用100次,它将为您分配100次内存。
And as for a tool, you can refer to Valgrind , which is a powerful tool to check whether there exists a memory error. 至于工具,您可以参考Valgrind ,这是一个功能强大的工具,可以检查是否存在内存错误。

If dynamically allocated memory is not freed, it results in a memory leak and system will run out of memory. 如果不释放动态分配的内存,则将导致内存泄漏,并且系统将耗尽内存。 This can lead to program crashing. 这可能导致程序崩溃。

主要是必须释放()分配的空间,但是必须确保在函数执行期间不要修改空间的值。

hey objective of call by reference is to modify the input pointer and return back to caller. 引用调用的目的是修改输入指针并返回给调用者。 means modified values ie address still with caller. 表示修改后的值,即仍与调用方联系。

You can simply do modification without allocate memory in your function 您可以简单地进行修改而无需在函数中分配内存

Just correction in your second approach 第二种方法只是纠正

void testfunc(int *c,int npts) { int i=0; 无效的testfunc(int * c,int npts){int i = 0;

for (i=0; i<npts; i++)
{
    c[i] += 10; //YOU JUST INCREMENT VALUE by 10 
}

} }

My approach to write function: 我写函数的方法:

  1. no memory allocation 没有内存分配
  2. no multiple arguments 没有多个参数
  3. keep necessary input, output argument , return value 保留必要的输入,输出参数,返回值
  4. here int *c, npts -- input argument, output [ your value modified in int *c location] 这里int * c,npts-输入参数,输出[您在int * c位置修改的值]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM