Malloc () crashes on Windows but not on Mac

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 malloc (). Why would there be any ideas to stop this?

Thanks!

Note. This, obviously, was originally part of a larger program, but I reduced the entire program to the above and tried only this code on both Mac and PC and reproduced the behavior.

+4
source share
4 answers

f does not yet indicate, therefore dereferencing it ( *f ) is invalid and has undefined behavior.

+7
source

You are assigning malloc-ed memory to * f, which is undefined since f is not initialized. Change to

 f = (FILE **)malloc( sizeof(FILE *)) 
+4
source

You must highlight f first

 f = (FILE **)malloc( sizeof(FILE *)) 

and then you can highlight for *f

 *f = (FILE *)malloc( sizeof(FILE)) 
+2
source

A common idiom for dynamic allocation is

 T *p = malloc(sizeof *p * num_elements); 

or

 T *p; ... p = malloc(sizeof *p * num_elements); 

So the correct way to highlight f :

 f = malloc(sizeof *f) 

Dumping in C is not needed, and discarding the malloc result is not recommended. Since the type of the expression *f is FILE * , sizeof *f same as sizeof (FILE *) , except that with sizeof *f you don't have to worry about making sure you have the right type.

+1
source

All Articles