简体   繁体   中英

malloc() and free() an array in c

I have been using Java and quite new to C. I tried to create a function that generates a random pixel array with malloc. I free the memory in another function after using that random array. I think my concept is just fine, but I wonder if I write the codes properly and it really frees the heap memory. It'd be great if you can look at the codes and see if it works.

pixel* randomPalette(int colors){

    int i, x;
    pixel * randomArr = (pixel *)malloc(sizeof(pixel)* colors);
    srand(time(NULL)); //generate a random seed
    for (i = 0; i < colors; i++){
        x = rand() % 256;
        randomArr[i].r = x; randomArr[i].g = x; randomArr[i].b = x;
    }
    return randomArr;
}

void QuantizeA(pixel* Im, int width, int height){
    //create a random palette of 8 RGB colors;
    const int num = 8;
    pixel* Arr = randomPalette(num);

    //find the min distance between pixel and palette color
    int x, y, z;
    int min = 195075; // max distance is 255^2 + 255^2 + 255^2
    int pos = 0;
    for (x = 0; x < height; x++){
        for (y = 0; y < width; y++){
            //compare distance of the pixel to each palette color
            for (z = 0; z < num; z++) {
                if (distance(Im[pos], Arr[z]) < min){
                    Im[pos].r = Arr[pos].r;
                    Im[pos].g = Arr[pos].g;
                    Im[pos].b = Arr[pos].b;
                }
            }
            pos++; //go to next piexl
        }
    }
    glutPostRedisplay();
    free(Arr);
}

From the memory allocation-deallocation part, your code is fine ( I did not check your logic ). However, two things to notice here,

  1. Check for the success of malloc() before using the returned value.
  2. You need to call srand(time(NULL)); only once at the start of your program, possibly in main() .

As a suggestion, you can always make use of the memcheck tool from valgrind to check for the memory leakage related issues, if you suspect any.

Also, please see this discussion on why not to cast the return value of malloc() and family in C . .

When you assign the new minimum distance:

Im[pos].r = Arr[pos].r;

you use the wrong index. It should be:

Im[pos].r = Arr[z].r;

As a side note: You cannot compare two structs with the comparison operators, not even for equality, but C allows you to assign one struct to another, which effectively copies the contents. So you don't need to copy all components, you can just say:

Im[pos] = Arr[z];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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