[RESOLVED] Validity of new/delete pair (or malloc/free) after pointer casting
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 10 of 10

Thread: [RESOLVED] Validity of new/delete pair (or malloc/free) after pointer casting

Threaded View

  1. #1
    Join Date
    Feb 2011
    Location
    United States
    Posts
    1,006

    [RESOLVED] Validity of new/delete pair (or malloc/free) after pointer casting

    Pretty much a simple question, but I wanted to confirm what I think I understood from reading elsewhere:

    Goal: To allocate some memory as a char*, read in some binary data, re-interpret it as a float* and then free the memory.

    My code looks like:

    Code:
    void someFunction(float* &result)
    {
        char * tmp = new char[1000];
    
        //...Fill the char buffer here...
    
        result = (float*)tmp; //Reinterpret binary data as floats
    }
    
    main(void)
    {
        float  * floatData;
        someFunction(floatData);
    
        //Do something
    
        delete[] (char*)floatData;  //Release the memory
    }
    Is the cast back to char* necessary on the red line (or could I have validly left it as float*)? Would it be different if I had written char * tmp = (char*)malloc(sizeof(char)*1000); on the blue line (and correspondingly used free (char*)floatData on the red line?

    Thanks for any guidance you might have.
    Last edited by BioPhysEngr; December 22nd, 2012 at 01:50 AM. Reason: Ah, my original code will segfault. Corrected syntax to pass the result pointer by referece.
    Best Regards,

    BioPhysEngr
    http://blog.biophysengr.net
    --
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center