CrazyEngineers
  • C programming doubt ?

    Sachin Jain

    Member

    Updated: Oct 25, 2024
    Views: 1.2K
    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....😔
    0
    Replies
Howdy guest!
Dear guest, you must be logged-in to participate on CrazyEngineers. We would love to have you as a member of our community. Consider creating an account or login.
Replies
  • gaurav.bhorkar

    MemberJan 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?
    Are you sure? This action cannot be undone.
    Cancel
  • csiscool

    MemberJan 2, 2011

    Nice Question..

    this code results in memory leak.
    Are you sure? This action cannot be undone.
    Cancel
  • Sachin Jain

    MemberJan 2, 2011

    @ csiscool
    Can you please explain more ?
    Are you sure? This action cannot be undone.
    Cancel
  • nansijs

    MemberApr 22, 2011

    I think the program cause memory leak. That is the allocated memory cannot be used by another application.
    Are you sure? This action cannot be undone.
    Cancel
  • pradeep_agrawal

    MemberApr 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
    Are you sure? This action cannot be undone.
    Cancel
  • vik001ind

    MemberMay 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.
    Are you sure? This action cannot be undone.
    Cancel
  • PraveenKumar Purushothaman

    MemberMay 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! 😀
    Are you sure? This action cannot be undone.
    Cancel
Home Channels Search Login Register