On 17 Sep, 11:48, Amit_Basnak <Amit.Bas...@gmail.com> wrote:
Dear Friends
I have two structures as below
typedef struct {
long_int length;
char data[1];
} CI_STRUCT_DATA;
typedef CI_STRUCT_DATA *ptr_CiStructData;
typedef struct {
char opener_ref_num_fmtd[26];
char our_ref_num[15];
char txn_ref_num[15];
char stop_tracer_date[27];
char tracer_trans_medium[3];
char tracer_frequency[2];
ptr_CiStructData MSG_DATA;
} CI_STRUCT_MSG;
I have allocated memory for it as below
CI_STRUCT_MSG msg_details;
msg_details.MSG_DATA = (CI_STRUCT_DATA *)
malloc( sizeof(CI_STRUCT_DATA) +(sizeof(unsigned
char)*(strlen(ptr_msg_details) + 1)) );
msg_details.MSG_DATA->length = strlen(ptr_msg_details);
strcpy((char *)msg_details.MSG_DATA->data,(char *)ptr_msg_details);
Im freeing up the memory as
free(ptr_msg_details);
Please suggest me any improvements in memory allocations if any
Thanks
Amit
I tend to use classes over structs for most things. But anyway, I
think new and delete are the prefered methods for memory allocation in
C++. You don't need to provide the size parameter, and new returns a
pointer to the object your creating.
I would do something like:
class CIData
{
public:
CIData();
~CIData();
const long_int getLength() const;
const char* getData() const;
void setLength(long_int len);
void setData(const char*);
private:
long_int m_Length;
char[1] m_Data;
};
class CIMsg
{
public:
CIMsg();
~CIMsg();
// Setters
void setMsgData(CIData *);
// .....
// Getters
// ......
private:
char opener_ref_num_fmtd[26];
char our_ref_num[15];
char txn_ref_num[15];
char stop_tracer_date[27];
char tracer_trans_medium[3];
char tracer_frequency[2];
const CIData * m_msgData;
}
int main(int argc, char** argv)
{
const CIMsg msgDetails;
const CIData data = new CIData();
msgDetails.setMsgData(CIData);
if(msgDetails)
{
// do some stuff
...
delete msgDetails;
msgDetails = NULL;
}
return 0;
}- Hide quoted text -
- Show quoted text -- Hide quoted text -
- Show quoted text -