Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

malloc() crashing on Windows but not on Mac

Tags:

c

malloc

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.

like image 245
Smalltown2k Avatar asked Dec 08 '22 19:12

Smalltown2k


2 Answers

f is not pointing anywhere yet, so dereferencing it (*f) is invalid and has an undefined behavior.

like image 183
MByD Avatar answered Dec 11 '22 09:12

MByD


You're assigning the malloc-ed memory to *f which is undefined behavior, since f is uninitialized. Change to

f = (FILE **)malloc( sizeof(FILE *))
like image 21
BlackBear Avatar answered Dec 11 '22 07:12

BlackBear