Thread: Any problem or memory leak here?

  1. #1
    Registered User
    Join Date
    Dec 2010
    Posts
    13

    Any problem or memory leak here?

    Hi,

    I have the following codes:
    Code:
    struct ABC {
      int x;
      float y;
      int z;
    }
    
    ...
    
    
    struct ABC *abc = malloc( sizeof( struct ABC ) );
    int *ptr = ( int* )abc;
    free( ptr );
    When I free ptr, is any memory leak here? since I force to change the data type from 'struct ABC*' to 'int*'.

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Probably not a memory leak, since malloc and free work on blocks of memory... but ar really bad thing to do programming wise since you didn't malloc ptr...

  3. #3
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    It's not a leak -- everything gets cast to a void* when you send it off to free() anyway, so what type you're using it as doesn't matter. The issue that was being pointed out is that, at least as written, you've got other copies of the pointer running around, which now all of a sudden are invalidated. If you're careful with how you pass your pointers around, you can make it work; but you'll have to be careful.

  4. #4
    Registered User
    Join Date
    Dec 2010
    Posts
    13
    The reason why I need this like that.

    I have an array which is int** ptrList which stores all pointers of struct XXX. And this array stores different struct, so it can't use a generic type.

    And the external handler able to pop the element from the array and handle with different struct.

  5. #5
    Registered User
    Join Date
    Dec 2010
    Posts
    13
    Thanks all of you!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Memory Problem with _beginthread()
    By nord in forum C Programming
    Replies: 3
    Last Post: 04-30-2009, 11:44 AM
  2. tools for finding memory leaks
    By stanlvw in forum C++ Programming
    Replies: 4
    Last Post: 04-03-2009, 11:41 AM
  3. Problems with shared memory shmdt() shmctl()
    By Jcarroll in forum C Programming
    Replies: 1
    Last Post: 03-17-2009, 10:48 PM
  4. Problem with linked list and shared memory
    By Sirfabius in forum C Programming
    Replies: 10
    Last Post: 11-10-2008, 04:45 PM
  5. Memory Problem - I think...
    By Unregistered in forum C Programming
    Replies: 4
    Last Post: 10-24-2001, 12:14 PM

Tags for this Thread