Home:ALL Converter>Free dynamically allocated memory in C

Free dynamically allocated memory in C

Ask Time:2021-01-09T11:07:09         Author:Subbir Rahman

Json Formatter

because I am new in C, I am not sure how to ask it, but here is my Code:

#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. How is it possible? I am testing some portion of my memory blocks. 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. To do so, I need to clear the memory that I have created inside the loop.

Thanks in advance

Author:Subbir Rahman,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/65638966/free-dynamically-allocated-memory-in-c
mydisplayname :

I think you'll want an array of pointers and then free those pointers after the loop.\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n \n#define ARRAY_SIZE 500\n \nint main(int argc, char *argv[]) {\n char * data[ARRAY_SIZE] = {0};\n for (int j=0; j<ARRAY_SIZE; ++j) {\n printf("Memory Size: %d\\n", j);\n int bytes = (1024*1024);\n data[j] = (char *) malloc(bytes);\n for(int i=0;i<bytes;i++){\n data[j][i] = (char) rand();\n }\n }\n for (int j=0; j<ARRAY_SIZE; ++j) {\n free(data[j]);\n }\n return 0;\n}\n",
2021-01-09T03:15:52
yy