Subbir Rahman
Subbir Rahman

Reputation: 45

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:

#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

Upvotes: 0

Views: 86

Answers (2)

mydisplayname
mydisplayname

Reputation: 356

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;
}

Upvotes: 2

dbush
dbush

Reputation: 223699

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.

You need to add a call to free at the bottom of the loop.

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);
}

Upvotes: 0

Related Questions