简体   繁体   English

在 C 中免费动态分配 memory

[英]Free dynamically allocated memory in C

because I am new in C, I am not sure how to ask it, but here is my Code:因为我是 C 的新手,我不知道怎么问,但这是我的代码:

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

#define ARRAY_SIZE 500

int main(int argc, char *argv[]) {

    for (int j=0; j<ARRAY_SIZE; ++j) {
        printf("Memory Size: %d\n", j);
        int bytes = (1024*1024);
        char *data;
        data = (char *) malloc(bytes);
        for(int i=0;i<bytes;i++){
            data[i] = (char) rand();
        }
    }
    //Free all Char*data that I have declared inside the for loop here
    return 0;

}

So I need to free my data variables that I have allocated inside the for loop.所以我需要释放我在 for 循环中分配的数据变量。 How is it possible?这怎么可能? I am testing some portion of my memory blocks.我正在测试我的 memory 块的某些部分。 So I am running it because I wanna see how far it goes.所以我运行它是因为我想看看它能走多远。 So the above code gets me to that point.所以上面的代码让我明白了这一点。 Now I am trying to run a loop below threshold point so that I can assure, the memory that I am working with is good and can sustain.现在我试图在阈值点以下运行一个循环,以便我可以保证,我正在使用的 memory 是好的并且可以维持。 To do so, I need to clear the memory that I have created inside the loop.为此,我需要清除在循环中创建的 memory。

Thanks in advance提前致谢

I think you'll want an array of pointers and then free those pointers after the loop.我认为您需要一个指针数组,然后在循环后释放这些指针。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
    
#define ARRAY_SIZE 500
    
int main(int argc, char *argv[]) {
    char * data[ARRAY_SIZE] = {0};
    for (int j=0; j<ARRAY_SIZE; ++j) {
        printf("Memory Size: %d\n", j);
        int bytes = (1024*1024);
        data[j] = (char *) malloc(bytes);
        for(int i=0;i<bytes;i++){
            data[j][i] = (char) rand();
        }
    }
    for (int j=0; j<ARRAY_SIZE; ++j) {
        free(data[j]);
    }
    return 0;
}

Since you assigned the return value of malloc to data which is defined inside of the loop, that memory is lost at the end of each iteration of the loop.由于您将malloc的返回值分配给在循环内部定义的data ,因此 memory 在循环的每次迭代结束时都会丢失。

You need to add a call to free at the bottom of the loop.您需要在循环底部添加对free的调用。

for (int j=0; j<ARRAY_SIZE; ++j) {
    printf("Memory Size: %d\n", j);
    int bytes = (1024*1024);
    char *data;
    data = (char *) malloc(bytes);
    for(int i=0;i<bytes;i++){
        data[i] = (char) rand();
    }
    free(data);
}

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

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