The following code:
#include<stdlib.h>
#include<stdio.h>
int main (void) {
FILE** f;
if ( (*f = (FILE *)malloc( sizeof(FILE *)) ) == NULL) {
printf("Out of RAM or some other disaster!\n");
return 1;
}
printf("OK!\n");
return 0;
}
compiles and runs without complaint on Mac OS X 10.8. However on Windows 7 (compiling with MinGW) it crashes on the malloc(). Why would this be and or any ideas to stop it happening?
Thanks!
Note: This was obviously originally part of a larger program but I've reduced the entire program to the above and tried just this code on both the Mac and PC and have replicated the behaviour.
f
is not pointing anywhere yet, so dereferencing it (*f
) is invalid and has an undefined behavior.
You're assigning the malloc-ed memory to *f which is undefined behavior, since f is uninitialized. Change to
f = (FILE **)malloc( sizeof(FILE *))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With