Question

When I use this fragment of code, instead of direct calling malloc() from init(), the error message appears under Windows 8. Standard message "Program ... stopped working".

Some of my programs generate same under windows 8. Under Linux everything is fine. Is win8's C language not ANSI compatible?

FILE *dumpfile;
double *cx;
void init_var(double *ptr) {
    ptr = malloc (L*sizeof(double));
    for (i=0; i<L; i++) ptr[i] = (double) i;
}

void init() {
//    cx = malloc (L*sizeof(double));
//    for (i=0; i<L; i++) cx[i] = i;
    init_var(cx);
    dumpfile = fopen( "dump.txt", "w" );
}

UPD. Aaaaargh. I get it now.

Was it helpful?

Solution

You are re-assigning a functiona argument inside the function, but that doesn't change the argument in the caller's context. This is because C is call by value.

You must pass init_var() the address of cx in order for it to change it:

void init_var(double **ptr)
{
  *ptr = malloc(L * sizeof **ptr);
  /* ... */
}

void init(void)
{
  init_var(&cx);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top