Segmentation fault on deleting a struct

I'm exentending existing C++ application. It have struct as below.

1
2
3
4
5
6
7
8
9
10
11
struct Message
{
	char	z_Date[10];
	char	z_Code[14];

	Message()
	{
		z_Date[0] = '\0';
		z_Code[0] = '\0';
	}
}

Then it has created a pointer to that struct as Message* pMsg = new Message(); and filled the Message variables. For ex. as below.
pMsg->z_Date has value "15/09";
pMsg->z_Code has value "ABCDEFGHIGHJ"

Then it has created a key using these z_Date and z_Code, insert that key in to map, and finally delete that pMsg pointer. That is something like that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
struct ltstr
{
	bool operator()(const char* s1, const char* s2) const	
	{		
		return strcmp(s1, s2) < 0;	
	}
};

map<const char*, int, ltstr>	map_test;
char	z_Key[40];
sprintf(z_Key,"%s%c%s",pMsg->z_Code,':',pMsg->z_Date);
std::map<const char*, int, ltstr>::iterator iteMap(map_test.find(z_Key));
if iteMap!= map_test.end())
{
	int i =   iteMap->second);
	//Continue the processing with thie int i here.
}
else
{	
	map_test.insert(make_pair(z_Key, 25));
}

//Here goes some code which use the pMsg.
delete pMsg;

//Here after map_test is using till the end of the program. 


Although this pMsg has deleted, after that map_test is used through out the entire program. The above mentioned code is working with out any issue.

Now what I need to do is change that key. In the above way z_Key is ABCDEFGHIGHJ:15/09. But now I need the key as ABCDEFGHIGHJ:1509 (by removing the middle /). So I did the following.

1
2
3
4
5
6
7
8
9
10
char zBuf[10];
strcpy(zBuf, pMsg->z_Date);
char zMonth[3];
char zDate[3];
strcpy(zMonth,zBuf+3);
zBuf[2] = '\0';
strcpy(zDate,zBuf);

char	z_Key[40];
sprintf(z_Key,"%s%c%s%s",pMsg->z_Code,':',zDate,zMonth);


Is this the best way to make the key? Although it gives the key correctly sometimes it gives a run time error(segmentation fault) at the line delete pMsg.

Can someone please help me on this.
All those temporary buffers and copying without length checking make me want to shut down.

Can you not find a safer way to build that key?
Topic archived. No new replies allowed.