C programming doubt ?

Sachin Jain

Sachin Jain

@sachin-0wuUmc Oct 25, 2024
Hey guys,
If I execute the following code, what will happen ?
int *ptr;
ptr = malloc(100);
ptr++;
free(ptr);


Now ptr points to 2nd integer block.
Now if i use free ptr (as shown in code) what will it do ?
Will it free the whole 100 byte memory or something else ?


Please reply....😔

Replies

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform

  • gaurav.bhorkar

    gaurav.bhorkar

    @gauravbhorkar-Pf9kZD Jan 2, 2011

    I think it will crash the program because you have created an invalid reference to the block of 100 bytes of allocated memory.

    I'm not sure though. Did the program run?
  • csiscool

    csiscool

    @csiscool-qA5mGA Jan 2, 2011

    Nice Question..

    this code results in memory leak.
  • Sachin Jain

    Sachin Jain

    @sachin-0wuUmc Jan 2, 2011

    @ csiscool
    Can you please explain more ?
  • nansijs

    nansijs

    @nansijs-Ulqfud Apr 22, 2011

    I think the program cause memory leak. That is the allocated memory cannot be used by another application.
  • pradeep_agrawal

    pradeep_agrawal

    @pradeep-agrawal-rhdX5z Apr 26, 2011

    Based on ANSI C specification, if the argument passed to free does not matches with value returned by malloc/calloc/realloc, or if the space has already been freed by calling free or realloc then the behavior is undefined.

    With this i feel the behavior can be different based on the compiler being used. If the code is compiled using gcc then the program will crash at free itself.

    -Pradeep
  • vik001ind

    vik001ind

    @vik001ind-rOaCSy May 13, 2011

    int *ptr; // this is a pointer of int type
    ptr = malloc(100);
    /* ERROR - malloc returns pointer of void type (void *), it is incompatible typecasting.
    Correct statement - ptr = (int *)malloc(100); Here we are dynamically allocating an array of 50 integers (considering 16 bit compiler). */
    ptr++; // PTR IS NOW POINTING TO NEXT INT
    free(ptr); // ERROR - deallocating the pointer which contains the wrong address. Allocation of memory is done to different address.

    Program may result in segmentation fault. Memory leak is a different concept altogether.
  • PraveenKumar Purushothaman

    PraveenKumar Purushothaman

    @praveenkumar-66Ze92 May 14, 2011

    I got System Error and as said here, it caused a memory issue... Since I worked on a virtual machine, it crashed the system too. I used 64 MB of RAM and when I restarted it, it was fine. 😐 It causes a Segmentation Fault! 😀