Thread: Trying to delete void* ?!

  1. #1
    Tears of the stars thames's Avatar
    Join Date
    Oct 2012
    Location
    Rio, Brazil
    Posts
    193

    Question Trying to delete void* ?!

    Good afternoon. How can I proceed to free the memory allocated to tmp?

    Code:
    /* 
     * File:   memswap.cpp
     * Author: thames
     *
     * Created on 7 de Janeiro de 2013, 14:46
     */
    
    #include <cstdlib>
    #include <iostream>
    #include <cstring>
    
    int swap(void* x, void* y, size_t size)
    {
       using std::memcpy;
        
       decltype(x) tmp;
       if( (tmp = new size_t) == nullptr)
        return -1;   
       memcpy(tmp, x, size);
       memcpy(x, y, size);
       memcpy(y, tmp, size);
       // delete tmp;
       
       return 0;
    }
    
    int main() {
    
        using std::cout;
        using std::endl;
        
        int x = 10; 
        int y = 20;
        size_t size = sizeof(int);
        if(swap(&x, &y, size) == 0)
        { 
          cout << x << " " << y << endl; 
          return EXIT_SUCCESS;
        }     
        else 
        {  
          cout << "An error has occurred.\n";    
          return EXIT_FAILURE;
        }
    }

  2. #2
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    What is the type of tml? dcltype? This does not even compile on my machine. Why not using the new keyword?
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  3. #3
    Registered User
    Join Date
    Aug 2010
    Location
    Poland
    Posts
    733
    1. new size_t allocates a block of exactly sizeof(size_t) bytes which is probably 4 or 8.
    2. You cannot delete void*. The only way to free the memory you are currently allocating is to cast the pointer to size_t* and then delete it.
    3. decltype(x) is a compile-time operator, which always returns void* in your case. "tmp" is always of type void*.
    4. If you want a universal swap for types other than trivially copyable (PODs), you must use templates. Note: std::swap already exists if you don't know.
    5. If you want to allocate and free a raw storage, use char* tmp = new char[size], then delete[] tmp.

    In other words, you should change your approach.
    Last edited by kmdv; 01-07-2013 at 11:42 AM.

  4. #4
    Tears of the stars thames's Avatar
    Join Date
    Oct 2012
    Location
    Rio, Brazil
    Posts
    193
    Note: std::swap already exists if you don't know.
    I already knew that. I'm starting to read a book called Mastering Algorithms with C which teaches Data Structures with C and there was a swap method in C using memcpy and I was trying to translate it to C++ . That cast made the trick!

    Code:
     
    delete (size_t*) tmp;
    decltype as kmdv pointed out, is a operator for deciding the type of the variable in compile time. (C++11 usage only).

  5. #5
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Yeah I read his post.. Well, the portability should always be on top
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  6. #6
    Tears of the stars thames's Avatar
    Join Date
    Oct 2012
    Location
    Rio, Brazil
    Posts
    193
    Yeah I read his post.. Well, the portability should always be on top http://im.cprogramming.com/images/smilies/wink.png
    haha

  7. #7
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by thames View Post
    I already knew that. I'm starting to read a book called Mastering Algorithms with C which teaches Data Structures with C and there was a swap method in C using memcpy and I was trying to translate it to C++ .
    To translate it to C++ you use the delete key on your keyboard and use the functionality the language provides.

    This code is horribly broken in so many ways that you cant imagine yet. I can think of seven major issues right off the bat:
    1. It allows non-copyable, non-swappable types to be swapped. Disaster for those objects, and nothing is detected at compile-time.
    2. It uses return values to indicate success or failure instead of exceptions.
    3. It assumes that a bitwise copy of objects will work, which is not true for certain classes such as those that contain pointers to their own members.
    4. A bitwise swap can be done without allocating any additional memory.
    5. The types are unknown here, so the appropriate member functions such as assignment operators cannot be called.
    6. The size must be passed in, which should not be required.
    7. The function should take references instead of pointers so that it doesn't have to deal with NULL pointers, which by the way you're failing to acount for.

    Your last post shows that you're calling the wrong version of delete too now.
    There is no way in hell this code should ever see the light of day. Attempting to use it in a real C++ program would be catastrophic.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  8. #8
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by thames View Post
    I already knew that. I'm starting to read a book called Mastering Algorithms with C which teaches Data Structures with C and there was a swap method in C using memcpy and I was trying to translate it to C++ ...
    Why are you trying to do such a thing? C is not C++!
    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.

  9. #9
    Tears of the stars thames's Avatar
    Join Date
    Oct 2012
    Location
    Rio, Brazil
    Posts
    193
    ok

    the original C code:

    Code:
    /* 
     * File:   memswap.c
     * Author: thames
     *
     * Created on 7 de Janeiro de 2013, 12:55
     */
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int swap(void* x, void* y, size_t size)
    {
       void* tmp;
       if( (tmp = malloc(size)) == NULL)
        return -1;   
       memcpy(tmp, x, size);
       memcpy(x, y, size);
       memcpy(y, tmp, size);
       free(tmp);
       
       return 0;
    }
    
    int main(int argc, char** argv) {
    
        int x = 10; 
        int y = 20;
        size_t size = sizeof(int);
        if(swap(&x, &y, size) == 0)
        { 
          printf("%d %d\n", x, y);
          return EXIT_SUCCESS;
        }     
        else 
        {  
          printf("%s\n", "An error has occurred.");    
          return EXIT_FAILURE;
        }
    }
    I already removed the C++ swap code I coded from my toolkit

  10. #10
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    To swap two areas of memory there is nothing that says the temporary storage has to be the same size as what is being swapped.

    You could (say) create a buffer that is a single char, and use a loop to swap individual characters in x and y.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  11. #11
    Registered User
    Join Date
    Aug 2003
    Posts
    1,218
    Or use templates (with added bonus of typesafety).

  12. #12
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    With the right checks to ensure that only POD types are passed, there is some theretical advantage to using memcpy. in C++11, there is std::is_trivially_copyable for this. But generally this swap is a useless micro-optimization.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  13. #13
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    Quote Originally Posted by iMalc View Post
    2. It uses return values to indicate success or failure instead of exceptions.
    On this, just to mention that new throws an bad alloc exception it doesn't return nullptr on error like malloc does. You can use
    Code:
    Type *t = new(std::nothrow) Type;
    to get the no-throw version that will return nullptr like malloc but it the exception seems easier as if you had 10 swaps you would need to check all those 10 swaps and probably won't be able to handle this case anyway

  14. #14
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by C_ntua View Post
    On this, just to mention that new throws an bad alloc exception it doesn't return nullptr on error like malloc does. You can use
    Code:
    Type *t = new(std::nothrow) Type;
    to get the no-throw version that will return nullptr like malloc but it the exception seems easier as if you had 10 swaps you would need to check all those 10 swaps and probably won't be able to handle this case anyway
    Good point, let me rephrase that:
    2. It tries (and fails) to use return values to indicate success or failure, instead of exceptions.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. error: invalid conversion from 'const void*' to 'void*'
    By Wahidin Wahid in forum C++ Programming
    Replies: 10
    Last Post: 04-17-2012, 02:17 AM
  2. error invalid conversion from ‘const void*’ to ‘void*’
    By Wahidin Wahid in forum C Programming
    Replies: 3
    Last Post: 03-27-2012, 08:18 PM
  3. Replies: 12
    Last Post: 03-27-2009, 02:36 PM
  4. how to delete void* pointer
    By benshi in forum C++ Programming
    Replies: 44
    Last Post: 12-21-2007, 06:17 PM
  5. Invalid conversion from 'const void*' to 'void*' error
    By prawntoast in forum C Programming
    Replies: 3
    Last Post: 05-01-2005, 10:30 AM

Tags for this Thread