Search code examples
carraysmallocfree

Free array returned from function


apologies if this has appeared elsewhere, I've not been able to find a clear answer. I've been using Ed S's answer, Option 1 (linked below) to allocate memory, populate the array, then return it back to the caller. He recommends freeing the memory after you've finished with it, however when I added the free() line, I get a core dump. I've had a poke around with GDB, but my skills probably aren't what the need to be.

Thanks in advance for any help you can give.

Link to answer: Returning an array using C

Code:

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

char * createArray();

int main(int argc, char *argv[]){
    printf("Creating Array...\n");
    // pointer to an int
    char *p;
    // size of the array
    int i,j;
    // width of array
    int width = 7;
    // height of array
    int height = 5;
    // get an array from the function
    p = createArray(width, height);
    // check if p was created properly
    if (p){
        // print out the array
        for (i = 0; i < width; ++i){
            for (j = 0; j < height; ++j){
                printf("[%c] ", *(p + (i * width) + j)); 
            }
        printf("\n");
        }

        // here's where it hits the fan
        free(p);
    }
    return 0;
}

char * createArray(int w, int h){
    // allocate some memory for the array
    char *r = malloc(w * h * sizeof(char));
    // check if the memory allocation was successful
    if(!r){
        return NULL;
    }
    int i, j;
    int count = 0;
    for (i = 0; i < w; ++i){
        for (j = 0; j < h; ++j){
            *(r + (i * w) + j) = 'X';
            ++count;
        }
    }
    return r;
}

Solution

  • You made a mistake on these lines

    *(r + (i * w) + j) = 'X';

    and

    printf("[%c] ", *(p + (i * width) + j));

    To keep inside the boundaries of your "2D" array -it's one dimensional but you are working around it like a compiler would-it should be i * length in there:

    *(r + (i * h) + j) = 'X';`
    

    and

    printf("[%c] ", *(p + (i * height) + j)); `
    

    If you use this, you should be able to stay within the boundaries without making a mess.