c++ - Character array reuse -
i'm writing win32 console application in visual studio 2010.
consider 1 function take 2 char*
parameters.
following prototype of function:
void writeapplicationfile(char *mappname,char* messagestring) { //do file related stuffs. }
now following calls working perfectly:
writeapplicationfile("firstone", "append me"); writeapplicationfile("firstone", "append another");
but if try same thing character array thing give me assertion, , throw me on assembly.
the following code not working:
char * localbuffer = new char[100]; sprintf(localbuffer,"number of jobs in queue %d",jobscount); writeapplicationfile("saazshadowprotect",localbuffer); free(localbuffer); localbuffer = null; //work fine. //... localbuffer = new char[100]; sprintf(localbuffer,"log file name %s",logfilecharname); writeapplicationfile("saazshadowprotect",localbuffer); free(localbuffer); // got assertion here.. localbuffer = null;
where going wrong?
one more thing want handle assertion , bugs try-catch block. how this?
if use new[]
must use delete[]
, not free()
or delete
. replace:
free(localbuffer);
with:
delete[] localbuffer;
there appears no reason dynamically allocating memory. size of buffer compile time constant, not large (no stack overflow) , buffer appears not required live beyond scope in allocated.
as c++ suggest using std::string
handle dynamic memory management , std::ostringstream
typesafe , avoids specification of fixed sized buffers instead of sprintf()
:
#include <sstream> #include <string> std::ostringstream out; out << "number of jobs in queue " << jobscount; const std::string s(out.str());
if access c-style string required use std::string::c_str()
.
additionally, argument types of writeapplicationfile()
char*
, not const char*
, passing string literal function causing undefined behaviour if function modifies arguments.
Comments
Post a Comment