Thread: valgrind Mismatch free() / delete /

  1. #1
    Registered User
    Join Date
    Nov 2016
    Posts
    26

    valgrind Mismatch free() / delete /

    Dear All,

    I got the valgrind report as below

    Mismatch free() / delete / delete []
    at 0x4006895: operator delete(void*) (vg_replace_malloc.c:480)
    by 0x8EA6D11: corefunction.

    I supect that it is expect me to write free() instead of delete p1.
    Given the the code.


    I have the structure.

    Code:
        struct Pack
        {
            unsigned int A;
            unsigned int B;
            unsigned int c;
            unsigned int D;    
        }
    
    
        int corefunction()
        {
    
    
            Pack *p1=new Pack;
            I filled the value for the p1 object.
            I called a virtual funcion by passing the p1 like this
            Send((void*)p1); //
    
    
            if(p1)
                delete p1;    // Here is the place where i have the doubt that wheher is it expecting to deallocate with free().
    
    
            return 0;
        }    
        
        bool Send(void* &get_SendData) 
        {  
            sendNextLevel(get_SendData  )
        }
            
        char* sendNextLevel(void* data)
        {
                        dataLen = sizeof(PackedSysTime);
    
    
                            Pack* txData = NULL;
                            txData = (Pack*)data;
        }

    since we have converted void pointer to struct without new operator like c-style casting, does it expecting us to write free while we deallocate the memory

    Thank you.
    Last edited by SAP_7; 11-03-2016 at 08:39 AM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,621
    You need to post some actual code we can compile and run with valgrind as well.

    Random snippets don't help.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,311
    The code should not compile: the parameter of Send is a non-const reference to void*, but the argument you passed is an rvalue result of a C-style cast to void*. It might compile with a Microsoft compiler's non-standard rvalue reference extension, but I don't remember the details of that and suggest that you avoid it anyway.

    Do you have control over the function signature of Send? If so, it looks like you don't need the reference in the first place, so get rid of it. If you have no control over it... well, I'm not sure what you're trying to do with the whole code snippet, so I'm not sure what to suggest. You could well do something like:
    Code:
    Pack* p1 = new Pack;
    void* temp = p1;
    Send(p1);
    delete p1;
    But maybe that's wrong because it could potentially modify temp without modifying p1, and maybe you need p1 to be modified in code that you did not show... or maybe just modifying what p1 (and hence temp) points to is good enough.

    Quote Originally Posted by SAP_7
    since we have converted void pointer to struct without new operator like c-style casting, does it expecting us to write free while we deallocate the memory
    No, that isn't the problem. Well, not normally anyway. Normally the cast just gives a rvalue reference that wouldn't mess around with the original, but then if you're involving a non-standard extension having to do with references, perhaps the rules are different.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    The defined behavior of new is to throw an exception if allocation fails, so if you make it to line 20, p1 will definitely have a value, and need to be freed with delete. The if statement is useless.
    What can this strange device be?
    When I touch it, it gives forth a sound
    It's got wires that vibrate and give music
    What can this thing be that I found?

  5. #5
    Registered User
    Join Date
    Nov 2016
    Posts
    26
    I suspect that Is structure object p1 getting the void pointer as a result of called function(Send)?
    Inside the Send function get_SendData is assigned with NULL value.

    while Send function come to calling function, will this have Null pointer value in the object(p1).
    If p1 is void pointer , will this delete p1 work fine?

    I am not sure about how to deallocate the void pointer?Despite being searched in the internet ,I still didn't get the clear answer



    Now you may all be able to understand

    Code:
    void main() { struct Pack { unsigned int A; unsigned int B; unsigned int c; unsigned int D; } Pack *p1=new Pack; Send((void*)p1); // After calling Send function, what will be the value of p1 pointer . Is it a null pointer since it is asssigned by null poiner in the called function? if(p1) delete p1; // Here is the place where i have the doubt that wheher is it expecting to deallocate with free(). return 0; } bool Send(void* &get_SendData) { sendNextLevel(get_SendData) char* _ucDataCmdReply; _ucDataCmdReply = new char[length]; get_SendData = (void*)_ucDataCmdReply // Here get_SendData is assigned with void pointer } char* sendNextLevel(void* data) { dataLen = sizeof(PackedSysTime); Pack* txData = NULL; txData = (Pack*)data; }
    Please help me on this.

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,621
    Your code doesn't compile.
    Code:
    $ g++ -Wall -Wextra -g main.cpp
    main.cpp:11:18: warning: unused parameter ‘get_SendData’ [-Wunused-parameter]
     void Send(void *&get_SendData)
                      ^
    main.cpp: In function ‘int corefunction()’:
    main.cpp:18:19: error: invalid initialization of non-const reference of type ‘void*&’ from an rvalue of type ‘void*’
       Send((void *) p1);            //
                       ^
    main.cpp:11:6: note:   initializing argument 1 of ‘void Send(void*&)’
     void Send(void *&get_SendData)
          ^
    With that in mind, I tried making it a simple pointer.
    Code:
    $ cat main.cpp
    #include <iostream>
    using namespace std;
    
    struct Pack {
      unsigned int A;
      unsigned int B;
      unsigned int c;
      unsigned int D;
    };
    
    //!! changed from reference to pointer to make it compile
    void Send(void *get_SendData)
    {
    }
    
    int corefunction()
    {
      Pack *p1 = new Pack;
      Send((void *) p1);            //
    
      if (p1)
        delete p1;                  // Here is the place where i have the doubt that wheher is it expecting to deallocate with free().
    
      return 0;
    }
    
    
    int main()
    {
      int x = corefunction();
      return x;
    }
    $ g++ -Wall -Wextra -g main.cpp
    main.cpp:12:17: warning: unused parameter ‘get_SendData’ [-Wunused-parameter]
     void Send(void *get_SendData)
                     ^
    $ valgrind --leak-check=full --show-leak-kinds=all ./a.out 
    ==4604== Memcheck, a memory error detector
    ==4604== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
    ==4604== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
    ==4604== Command: ./a.out
    ==4604== 
    ==4604== 
    ==4604== HEAP SUMMARY:
    ==4604==     in use at exit: 72,704 bytes in 1 blocks
    ==4604==   total heap usage: 2 allocs, 1 frees, 72,720 bytes allocated
    ==4604== 
    ==4604== 72,704 bytes in 1 blocks are still reachable in loss record 1 of 1
    ==4604==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
    ==4604==    by 0x4EC3EFF: ??? (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21)
    ==4604==    by 0x40104E9: call_init.part.0 (dl-init.c:72)
    ==4604==    by 0x40105FA: call_init (dl-init.c:30)
    ==4604==    by 0x40105FA: _dl_init (dl-init.c:120)
    ==4604==    by 0x4000CF9: ??? (in /lib/x86_64-linux-gnu/ld-2.23.so)
    ==4604== 
    ==4604== LEAK SUMMARY:
    ==4604==    definitely lost: 0 bytes in 0 blocks
    ==4604==    indirectly lost: 0 bytes in 0 blocks
    ==4604==      possibly lost: 0 bytes in 0 blocks
    ==4604==    still reachable: 72,704 bytes in 1 blocks
    ==4604==         suppressed: 0 bytes in 0 blocks
    ==4604== 
    ==4604== For counts of detected and suppressed errors, rerun with: -v
    ==4604== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
    $
    Now aside from the leak in the standard library, there is nothing wrong with the code you posted.

    You NEED to post some code which demonstrates the actual problem, because there is no way for us to make any guesses as to how you've screwed up based on what you posted.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  7. #7
    Registered User
    Join Date
    Nov 2016
    Posts
    26
    It's big and legacy.it could not be posted. Could you tell how to deallocate the void pointer.In the above code if p1 is null pointer,what could be the result.BEcause that's the reason i am getting the
    Mismatched free() / delete / delete []
    at 0x4006895: operator delete(void*) (vg_replace_malloc.c:480)



    Code:
    struct Pack {
      unsigned int A;
      unsigned int B;
      unsigned int c;
      unsigned int D;
    };
    
    
    int main()
    {
      int x = corefunction();
      return x;
    }
    int corefunction()
    {
      Pack *p1 = new Pack;
      Send((void *) p1);            //
    
      if (p1)
        delete p1;                  // Here is the place where i have the doubt that wheher is it expecting to deallocate with free().
    
      return 0;
    }
     
    void Send(void * &get_SendData)
    {
           char *c1=new char[23];
            c1="GetNumber";
            get_data=(void *) c1;



    }

    Last edited by SAP_7; 11-04-2016 at 05:12 AM. Reason: Include the code

  8. #8
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,621
    Perhaps you need to learn some C/C++.
    Code:
    char *c1=new char[23];
            c1="GetNumber";
            get_data=(void *) c1;
    You're trashing c1 by making it point to something which you DIDN'T allocate (hence the mis-match).

    Maybe if you did this
    Code:
    char *c1=new char[23];
    strcpy(c1,"GetNumber");
            get_data=(void *) c1;
    You would be able to delete[] c1; without it complaining.

    Making a copy of a pointer and casting it to a different type doesn't change where it points to.
    Where it points to is all that malloc/free care about.
    The original new type is an additional requirement that delete cares about.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  9. #9
    Registered User
    Join Date
    Nov 2016
    Posts
    26
    Quote Originally Posted by Salem View Post
    Perhaps you need to learn some C/C++.
    Code:
    char *c1=new char[23];
            c1="GetNumber";
            get_data=(void *) c1;
    You're trashing c1 by making it point to something which you DIDN'T allocate (hence the mis-match).

    Maybe if you did this
    Code:
    char *c1=new char[23];
    strcpy(c1,"GetNumber");
            get_data=(void *) c1;
    You would be able to delete[] c1; without it complaining.

    Making a copy of a pointer and casting it to a different type doesn't change where it points to.
    Where it points to is all that malloc/free care about.
    The original new type is an additional requirement that delete cares about.
    very thanks for your quick reponse.!!!

    I posted the code which is in the application


    could you please make this code to run without removing pointer or reference.since with the same kind of code i am getting the error.
    I am trying to find out why am i getting the mismatch error in the application.I suspect that i am trying to deallocate the void pointer with delete.

    Mismatched free() / delete / delete []at 0x4006895: operator delete(void*) (vg_replace_malloc.c:480)


    I am not sure why am i getting the Mismatch delete , free with the below code.


    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <iostream>
    #include <time.h>
    #include<string.h>
    using namespace std;
    void sendData(void* &get_data)
    {
            char *c1=new char[23];
            //strcpy(c1,"GetNumber");
            c1="sdfsjkdhf";
            cout<<c1;
            get_data=(void *) c1;
    
    
    }
    struct Packet
            {
            unsigned short tm_sec;  // 16 bit Range 0-59
            unsigned short tm_min;  // 16 bit Range 0-59
            unsigned short tm_hour; // 16 bit Range 0-23
            unsigned short tm_mday; // 16 bit  Range 1-31
            unsigned short tm_mon;  // 16 bit  Range 0-11
            unsigned short tm_year; // 16 bit  Since 1900
            };
    
    
    int main(void)
    {
    
    
            time_t rawtime = time(NULL);
            struct tm * timeinfo = NULL;
            timeinfo = (struct tm *) localtime(&rawtime);
    
    
     Packet *p_chld1=new Packet;
    
    
            p_chld1->tm_sec=timeinfo->tm_sec;
            p_chld1->tm_min=timeinfo->tm_min;
            p_chld1->tm_hour=timeinfo->tm_hour;
            p_chld1->tm_mday=timeinfo->tm_mday;
            p_chld1->tm_mon=timeinfo->tm_mon;
            p_chld1->tm_year=timeinfo->tm_year;
    
    
    
    
            char *timeStamptmp = new char[256];
    
    
            if(timeinfo)
            {
                    strftime(timeStamptmp,256,"%T, %m-%d-%Y",timeinfo);
            }
    
    
            sendData((void *) p_chld1);
    
    
    
    
    
    
            if (timeStamptmp)
                     delete []timeStamptmp;
    
    
            if(p_chld1)
                    delete p_chld1;
            return 0;
    }


  10. #10
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Code:
            char *c1=new char[23];
            //strcpy(c1,"GetNumber");
            c1="sdfsjkdhf";
    Like you've been told, this doesn't work.
    The statement c1 = "..." assigns a new pointer to c1. This was not allocated by new, hence it cannot be freed with delete.
    Just get yourself up to speed a bit and use std::string.

    std::string s;
    s = "..."; // OK
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  11. #11
    Registered User
    Join Date
    Nov 2016
    Posts
    26
    Could you tell me the posiblities of the reason to get the Mismatched free() / delete / delete [].

    I unable to see the line no in the valgrind report. it displays the function name. with that funciton name, i am not able to find where exactly the issue is there.I am gettng the Mismatched free() / delete / delete [].

    Thanks in Advance.

  12. #12
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,621
    Here are some examples of things NOT to do.
    Code:
    int main ( ) {
      int a;
      free(&a);  //!! oops, you didn't malloc this
    }
    
    ==5014== Invalid free() / delete / delete[] / realloc()
    ==5014==    at 0x4C2EDEB: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
    ==5014==    by 0x4005B8: main (main.c:6)
    ==5014==  Address 0xffefffd64 is on thread 1's stack
    ==5014==  in frame #1, created by main (main.c:4)
    Code:
    int main ( ) {
      char *p = malloc(10);
      free(p);  // OK
      free(p);  //!! oops, you did this already
    }
    
    ==5022== Invalid free() / delete / delete[] / realloc()
    ==5022==    at 0x4C2EDEB: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
    ==5022==    by 0x400593: main (main.c:7)
    ==5022==  Address 0x5203040 is 0 bytes inside a block of size 10 free'd
    ==5022==    at 0x4C2EDEB: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
    ==5022==    by 0x400587: main (main.c:6)
    Code:
    int main ( ) {
      char *p = malloc(10);
      for ( int i = 0 ; i < 10 ; i++ )
        *p++ = '\0';
      free(p);  //!! oops, you messed with the pointer to the START of the memory
    }
    
    ==5032== Invalid free() / delete / delete[] / realloc()
    ==5032==    at 0x4C2EDEB: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
    ==5032==    by 0x4005A9: main (main.c:8)
    ==5032==  Address 0x520304a is 0 bytes after a block of size 10 alloc'd
    ==5032==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
    ==5032==    by 0x400577: main (main.c:5)
    Code:
    int main ( ) {
      char *p = malloc(10);
      free(p);
      //!! oops, you already freed the memory
      for ( int i = 0 ; i < 10 ; i++ ) {
        p[i] = '\0';
      }
    }
    
    ==5047== Invalid write of size 1
    ==5047==    at 0x40059E: main (main.c:9)
    ==5047==  Address 0x5203040 is 0 bytes inside a block of size 10 free'd
    ==5047==    at 0x4C2EDEB: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
    ==5047==    by 0x400587: main (main.c:6)
    And in C++
    Code:
    int main ( ) {
      char *p = new char;  // just one char
      delete [] p;  //!! oops, you didn't call new[]
    }
    
    ==5079== Mismatched free() / delete / delete []
    ==5079==    at 0x4C2F74B: operator delete[](void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
    ==5079==    by 0x40076E: main (main.cpp:6)
    ==5079==  Address 0x5ab5c80 is 0 bytes inside a block of size 1 alloc'd
    ==5079==    at 0x4C2E0EF: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
    ==5079==    by 0x400757: main (main.cpp:5)
    Code:
    int main ( ) {
      char *p = new char[10];  // 10 chars
      delete p;  //!! oops, you called new[]
    }
    
    ==5093== Mismatched free() / delete / delete []
    ==5093==    at 0x4C2F24B: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
    ==5093==    by 0x400767: main (main.cpp:6)
    ==5093==  Address 0x5ab5c80 is 0 bytes inside a block of size 10 alloc'd
    ==5093==    at 0x4C2E80F: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
    ==5093==    by 0x400757: main (main.cpp:5)
    Code:
    int main ( ) {
      char *p = new char[10];  // 10 chars
      free(p);  //!! oops, you called new[]
    }
    
    ==5107== Mismatched free() / delete / delete []
    ==5107==    at 0x4C2EDEB: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
    ==5107==    by 0x400767: main (main.cpp:7)
    ==5107==  Address 0x5ab5c80 is 0 bytes inside a block of size 10 alloc'd
    ==5107==    at 0x4C2E80F: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
    ==5107==    by 0x400757: main (main.cpp:6)
    If you read the rest of the messages carefully, it will tell you which particular combination of malloc / free / new / new[] / delete / delete[] you've messed up.


    > I unable to see the line no in the valgrind report.
    Then compile with the -g flag to enable symbols.
    Compare these two runs with different compilation flags.
    Code:
    $ gcc -Wall main.c
    $ valgrind ./a.out 
    ==4952== Memcheck, a memory error detector
    ==4952== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
    ==4952== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
    ==4952== Command: ./a.out
    ==4952== 
    ==4952== Invalid write of size 1
    ==4952==    at 0x40059E: main (in /home/sc/Documents/a.out)
    ==4952==  Address 0x5203040 is 0 bytes inside a block of size 10 free'd
    ==4952==    at 0x4C2EDEB: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
    ==4952==    by 0x400587: main (in /home/sc/Documents/a.out)
    ==4952==  Block was alloc'd at
    ==4952==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
    ==4952==    by 0x400577: main (in /home/sc/Documents/a.out)
    ==4952== 
    ==4952== 
    ==4952== HEAP SUMMARY:
    ==4952==     in use at exit: 0 bytes in 0 blocks
    ==4952==   total heap usage: 1 allocs, 1 frees, 10 bytes allocated
    ==4952== 
    ==4952== All heap blocks were freed -- no leaks are possible
    ==4952== 
    ==4952== For counts of detected and suppressed errors, rerun with: -v
    ==4952== ERROR SUMMARY: 10 errors from 1 contexts (suppressed: 0 from 0)
    
    $ gcc -Wall -g main.c
    $ valgrind ./a.out 
    ==4963== Memcheck, a memory error detector
    ==4963== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
    ==4963== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
    ==4963== Command: ./a.out
    ==4963== 
    ==4963== Invalid write of size 1
    ==4963==    at 0x40059E: main (main.c:8)
    ==4963==  Address 0x5203040 is 0 bytes inside a block of size 10 free'd
    ==4963==    at 0x4C2EDEB: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
    ==4963==    by 0x400587: main (main.c:6)
    ==4963==  Block was alloc'd at
    ==4963==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
    ==4963==    by 0x400577: main (main.c:5)
    ==4963== 
    ==4963== 
    ==4963== HEAP SUMMARY:
    ==4963==     in use at exit: 0 bytes in 0 blocks
    ==4963==   total heap usage: 1 allocs, 1 frees, 10 bytes allocated
    ==4963== 
    ==4963== All heap blocks were freed -- no leaks are possible
    ==4963== 
    ==4963== For counts of detected and suppressed errors, rerun with: -v
    ==4963== ERROR SUMMARY: 10 errors from 1 contexts (suppressed: 0 from 0)
    $
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  13. #13
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Another good example:

    Code:
    char* s = new char[50];
    s = "Hello World!"; // Oops, replaces the pointer to the allocated memory
    delete [] s; // Oops, can't delete memory we didn't allocate with new.
    Fix:
    Code:
    std::string s;
    s = "Hello World!"; // No problem!
    //delete [] s; // Not needed!
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  14. #14
    Registered User
    Join Date
    Mar 2016
    Posts
    203
    Salem/Elysia: thank you for your various illustrative examples. Not just for the OP, but these example very helpful for others like me too. I don't want to hijack the thread but if you/other BoardGuru's can think of any additional examples in line with the contents of this thread, it would be interesting to note those too.

  15. #15
    Nasal Demon Xupicor's Avatar
    Join Date
    Sep 2010
    Location
    Poland
    Posts
    179
    I'm no guru, but there you go:
    Code:
    #include <iostream>
    #include <memory>
    #include <cstdlib>
    
    class Data {
        static int next_id;
        int id;
    public:
        Data() : id(++next_id) {
            std::cerr << '#' << id << ":\t" << __PRETTY_FUNCTION__ << '\n';
        }
        
        ~Data() {
            std::cerr << '#' << id << ":\t" << __PRETTY_FUNCTION__ << '\n';
        }
    };
    int Data::next_id = 0;
    
    int main() {
        {
            auto collection = new Data[3];
            delete[] collection;
        }
        std::cerr << "---\nBad release follows:\n";
    
        { // notice the destructors firing (or not)
            auto badly_released_collection = new Data[3];
            //uncomment one of the following and observe the effects
            //delete badly_released_collection; // we should have used delete[], or even better - std::vector
            //free(badly_released_collection);  // don't mix different ways of allocation/deallocation
            
            //what we should have done, of course:
            //delete[] badly_released_collection;
        }    
        // the program may crash if you misuse delete/free above
        
        std::cerr << "---\nSmart pointer abuse follows:\n";
        { // smart pointers can be abused too!
            std::unique_ptr<Data> wait_what(new Data[3]);
            // vs
            //std::unique_ptr<Data[]> wait_what(new Data[3]);
            // and:
            //auto wait_what = std::make_unique<Data[]>(3);
            // of course, std::vector would be even better :P
        }
    }
    Even if it won't crash and burn - you can leak memory and/or resources. Imagine you're closing an external resource in the destructor. If it never fires - you may have a problem.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. using delete and free
    By Pulock2009 in forum C Programming
    Replies: 4
    Last Post: 09-10-2010, 09:20 AM
  2. New/delete vs malloc/free
    By KBriggs in forum C++ Programming
    Replies: 6
    Last Post: 07-07-2009, 03:08 PM
  3. Replies: 17
    Last Post: 11-16-2006, 09:06 PM
  4. malloc & free in C vs. new & delete in C++
    By groberts1980 in forum C Programming
    Replies: 20
    Last Post: 10-17-2006, 10:00 PM
  5. free() or delete?
    By Trauts in forum C++ Programming
    Replies: 7
    Last Post: 05-14-2003, 04:20 PM

Tags for this Thread