Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to malloc an array in a called function but free it in the calling function?

Tags:

c

I'm not an expert in C, but here's what I'm trying to do:

int main(void) {
    double *myArray;
    ...
    myFunction(myArray);
    ...
    /* save myArray contents to file */
    ...
    free(myArray);
    ...
    return 0;
}

int myFunction(double *myArray) {
    int len=0;
    ...
    /* compute len */
    ...
    myArray = malloc( sizeof(double) * len );
    if (myArray == NULL) 
      exit(1);
    ...
    /* populate myArray */
    ...
    return 0;
}

I'd like to save the contents of myArray inside main, but I don't know the size required until the program is inside myFunction.

Since I'm using CentOS 6.2 Linux, which I could only find a gcc build available up to 4.4.6 (which doesn't support C99 feature of declaring a variable-length array; see "broken" under "Variable-length arrays in http://gcc.gnu.org/gcc-4.4/c99status.html), I'm stuck using -std=c89 to compile.

like image 594
ggkmath Avatar asked Feb 18 '23 10:02

ggkmath


2 Answers

Simple answer is no.

You are not passing back the pointer.

use

int main(void) {
    double *myArray;
    ...
    myFunction(&myArray);
    ...
    /* save myArray contents to file */
    ...
    free(myArray);
    ...
    return 0;
}

int myFunction(double **myArray) {
    int len=0;
    ...
    /* compute len */
    ...
    *myArray = malloc( sizeof(double) * len );
    if (NULL == *myArray) 
      exit(1);
    ...

EDIT

    poputateThis = *myArray;

    /* populate poputateThis */

END OF EDIT

    ...
    return 0;

EDIT

Should simplify thigs for your }

like image 180
Ed Heal Avatar answered Mar 03 '23 22:03

Ed Heal


What you are doing is not OK since myFunction doesn't change the value myArray holds in main; it merely changes its own copy.

Other than that, it's OK even if stylistically debatable.

like image 41
cnicutar Avatar answered Mar 03 '23 21:03

cnicutar