int main()
{
    FILE *fp;
    unsigned long size;
    unsigned char *loc;
    fp=fopen("Hello.exe","rb");
    if(fp==NULL)
    {
        printf("\nCouldn't load file");
        getchar();
        return 0;
    }

    fseek(fp,0,SEEK_END);
    size = ftell(fp);

    fseek(fp,0,SEEK_SET);

    loc=(unsigned char*)malloc(sizeof(size));
    printf("\nSize of  file is : %d",size);
    if(loc==NULL){
    printf("\nError in allocating memory.");

    }
    printf("\nFread called");
    fread(loc,size,1,fp);
    printf("\nFread fails:");


    return 0;
}

I was trying to load a "Hello World" application into heap and this fread hangs me out.
Can anybody figure out why is this happening out!

Dani AI

Generated

Most likely root cause: the allocation line. As implied, malloc(sizeof(size)) allocates the size of the variable size (typically 4 or 8 bytes), not the file length. fread then writes past that tiny buffer and you get undefined behaviour (hang, crash, whatever). That’s far more likely than an AV lock (thanks to for the tip — still worth checking).

A safe minimal pattern:

/* get file length */
fseek(fp, 0, SEEK_END);
long t = ftell(fp);
if (t < 0) /* handle error */;
size_t len = (size_t)t;
rewind(fp);

/* allocate and read */
unsigned char *buf = malloc(len + 1);
if (!buf) /* handle OOM */;
size_t got = fread(buf, 1, len, fp);
if (got != len) /* check ferror/feof and handle */;
buf[len] = '\0'; /* only if you need a string */
free(buf);

Practical checks and tips:

  • Always check return values of fopen, fseek, ftell and fread — they tell you the real error.
  • Use fread(buf, 1, len, fp) and compare the returned count to len.
  • Fix your printf format: use %zu for size_t or %lu for unsigned long.
  • If the file is huge use streaming/mmap instead of allocating the whole file.
  • If you still see a block, try disabling AV or copy the file to another location to rule out locks; also run under a debugger or valgrind/ASAN to catch overruns.

Those steps will make the problem reproducible and safe to fix.

Recommended Answers

All 2 Replies

anti-virus software

fread is fine. Look at a line 19. How much memory did you allocate?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.