因为我是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;
}
因此,我需要释放在for循环内分配的数据变量。这怎么可能?我正在测试部分内存块。所以我正在运行它,因为我想看看它走了多远。因此,以上代码使我明白了这一点。现在,我正在尝试在阈值以下运行一个循环,以便可以确保我正在使用的内存良好并且可以维持。为此,我需要清除在循环内部创建的内存。
提前致谢
我认为您需要一个指针数组,然后在循环后释放这些指针。
#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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句