visual studio 2008 - Free Allocated Memory Generates Exception - C++ -


there function in application in memory allocated formatting port name. createfile called open port. @ end of function free called attempt free allocated memory.

dword cserialport::open( wchar_t * port ) {     dcb dcb = {0};     lpthread_start_routine pthreadstart;     void * pvthreaddata = null;     wchar_t * pwcportname = null;     dword dwretval = error_success;      /* validate parameters. */      pwcportname = (wchar_t *)malloc( wcslen( port ) + 6 );      if ( pwcportname == null )     {         trace(_t("cserialport::open : failed allocate memory formatted serial port name.\r\n\terror: %d\r\n\tfile: %s\r\n\tline: %d\r\n"), error_not_enough_memory, __wfile__, __line__);         return error_not_enough_memory;     }      memcpy( pwcportname, l"\\\\.\\", 4 * 2 );     memcpy( pwcportname + 4, port, wcslen( port ) * 2 + 2 );      // handle serial port.     _hserialport = createfile(         pwcportname,                    // formatted serial port         generic_read | generic_write,   // access: read , write         0,                              // share: no sharing         null,                           // security: none         open_existing,                  // om port exists         file_flag_overlapped,           // asynchronous i/o         null                            // no template file com port         );      if ( _hserialport == invalid_handle_value )     {         trace(_t("cserialport::open : failed handle serial port.\r\n\terror: %d\r\n\tfile: %s\r\n\tline: %d\r\n"), ::getlasterror(), __wfile__, __line__);         return ::getlasterror();     }      /* initialize dcb structure com port parameters buildcommdcb. */      /* set serial port communications events mask setcommmask. */      /* set serial port parameters setcommstate. */      /* set serial port communications timeouts setcommtimeouts. */      /* create thread handle received data createthread. */      free( pwcportname );                 // <-- exception thrown here.      return dwretval; } 

can tell me i'm doing wrong? thanks.

malloc allocates bytes, using allocated memory store wchar_t.

you have change malloc size parameter match existing memcpy usage:

pwcportname = (wchar_t *)malloc( wcslen( port ) + 6 ); 

should be

pwcportname = (wchar_t *)malloc( (wcslen( port ) + 6) * sizeof(wchar_t)); 

Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -