0

I have a simple program that allocates memory, and copy a file from resource to that memory space, but the problem is the program exit after calling malloc function without any exception or errors. I use VS2010 express, I put a breakpoint, and when I hit F10 (step over) the program exits. here's the code :

int main(void){

    HRSRC rInfo;
    HGLOBAL rPointer;
    PVOID filePointer;
    int fileSize;
    unsigned char *buffer;


    rInfo = FindResourceA(0, MAKEINTRESOURCE(101), RT_RCDATA);
    if(rInfo == NULL){
        return 0;
    }

    rPointer = LoadResource(NULL, rInfo);
    if(rPointer == NULL){
        return 0;
    }

    filePointer = LockResource(rPointer);
    if(filePointer == NULL){
        return 0;
    }

    fileSize = SizeofResource(0, rInfo);
    if(fileSize == 0){
        return 0;
    }


    buffer = (unsigned char *)malloc(fileSize); // <-- breakpoint here
    if(buffer == NULL){
        MessageBoxA(0, "Error allocating memory.", "My App", 0);
    }else{
        MessageBoxA(0, "Allocating memory done without errors.", "My App", 0);
    }
    memcpy(buffer, stubPointer, stubSize);
}

I've verified the size returned by SizeofResource(0, rInfo); (1024 bytes, using debugger) I don't know if you want more infos. let me know if.

Nadjib Dz
  • 71
  • 6
  • 5
    [Do not cast the return value of `malloc()`](http://stackoverflow.com/a/605858/1983495), this wount fix the issue, but you should not do it. – Iharob Al Asimi Mar 16 '15 at 12:26
  • What happens if you dont put breakpoint?Dont cast result of `malloc` and try compiling the code.Have you included `stdlib.h`? – Vagish Mar 16 '15 at 12:26
  • In c++ you can use `new` or if you must use `malloc()` because you want to `realloc()` later for example, then let the cast be a c++ cast like `reinterpret_cast(malloc(fileSize))`. Please read the link. And if this is a c++ question then there is a problem with the tags. – Iharob Al Asimi Mar 16 '15 at 12:28
  • are u using a tailored linker script ? – theadnangondal Mar 16 '15 at 12:29
  • I removed the cast, run it outside the debugger, include `stdlib.h`, same result. But when I moved the source file to a new fresh project it works just fine !!! I think it has something with compiler/linker options, i'll post it here if I find the options causes this. thanks averyone – Nadjib Dz Mar 16 '15 at 12:58
  • @NadjibDz in that case, I'd recommend doing a "clean solution" on the original project. – Drew McGowen Mar 16 '15 at 13:32
  • Although this question has a C tag, it lists VS2010, which I'm pretty certain is a C++ compiler. Hence any suggestion to not cast the return value from malloc are irrelevant. – paxdiablo May 18 '15 at 04:47

0 Answers0