简体   繁体   中英

Dynamic memory allocation in c using malloc

Allocated a 50*sizeof(int) of dynamic memory using malloc . As I read in some document the immediately below element should be a size of allocated memory using malloc (In my case it is 200 bytes). But when i executed this below code, got 209 instead 200!

    #include<stdio.h>
    #include<malloc.h>
    int main()
    {
        int *p = (int *)malloc(sizeof(int)*50);

        int i;

        for(i = 0; i < 5; i++)
            scanf("%d", &p[i]);

        for(i = -1; i < 5; i++)
            printf(" %d ", *((int *)(p+i)));
        free(p);
    }

Can somebody help whats wrong?

The problem is in the first iteration of

for(i=-1;i<5;i++)
        printf(" %d ",*((int *)(p+i)));

here, the index -1 refers to an invalid memory location and attempt to access that invokes undefined behavior .

FWIW, There is no wrap-around for array indexing in C, it's simple pointer arithmetic and as soon as you point outside the allocated memory region, you hit UB.

That said,

This is undefined behavior. You're accessing memory that is outside the region that malloc() returned and this is not valid.

If it was valid in some context, that was an implementation-specific extension and not something you can depend on or do in the general case.

Also, please don't cast the return value of malloc() in C. The printing could just be:

printf(" %d ", p[i]);

the asterisk and cast that you added are not necessary, just use array indexing.

Tell me the document where you have seen written that the elemnt below malloc()'s return address telles the size of malloc(). I have just read man-page of malloc() but I couldn't find and have never heard of it before. I think you're confused. There's no way to find out the size of dynamically allocated memory unless you keep it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM