这代码安全么?

周晓荣 2011-09-21 10:25:33
最怕写服务端的代码了,自从让服务器奔溃过一次后,有心里阴影,请各位狼友们帮我看看下面那段代码有没有安全问题,最主要是有没有泄漏或线程安全问题,谢谢。


#pragma warning (disable: 4786)
#include <windows.h>
#include <map>
#include <string>
#include "GetIvrDeviceID.h"
using namespace std;

//Global Variable
map <long, string> g_map_deviceid;
CRITICAL_SECTION g_cs;
long g_count = 0;


void InitMapCriticalSection(void)
{
if (1 == InterlockedIncrement(&g_count))
{
InitializeCriticalSection(&g_cs);
}
return ;
}

void SetFinishToDevice(long call_id, const char *p_deviceid)
{
try
{
EnterCriticalSection(&g_cs);
g_map_deviceid.insert(map <long, string>::value_type(call_id, p_deviceid));
LeaveCriticalSection(&g_cs);
}
catch(...)
{
return ;
}
return ;
}

//根据call_id获取finish_to_device,获取后自动删除该纪录,所以不可重复查询
int CanGetFinishToDevice(long call_id, char *p_deviceid)
{
map <long, string>::iterator it;

try
{
EnterCriticalSection(&g_cs);
it = g_map_deviceid.find(call_id);

if (g_map_deviceid.end() != it)
{
strcpy( p_deviceid, it->second.c_str() );
g_map_deviceid.erase(it);

LeaveCriticalSection(&g_cs);
return 1;
}
else
{
LeaveCriticalSection(&g_cs);
return 0;
}
}
catch (...)
{
return 0;
}
}


void FreeMapSource(void)
{
if (0 == InterlockedDecrement(&g_count))
{
DeleteCriticalSection(&g_cs);
}
return ;
}


...全文
99 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
周晓荣 2011-09-21
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 liveeng 的回复:]

C/C++ code

strcpy( p_deviceid, it->second.c_str() );



溢出了
[/Quote]
这个是得注意下
ghost5216 2011-09-21
  • 打赏
  • 举报
回复

int CanGetFinishToDevice(long call_id, char *p_deviceid)
{
map <long, string>::iterator it;

try
{
EnterCriticalSection(&g_cs);
it = g_map_deviceid.find(call_id);

if (g_map_deviceid.end() != it)
{
strcpy( p_deviceid, it->second.c_str() );
g_map_deviceid.erase(it);

LeaveCriticalSection(&g_cs);
return 1;
}
else
{
LeaveCriticalSection(&g_cs);
return 0;
}
}
catch (...)
{
return 0;
}
}


catch处理中应该加入
LeaveCriticalSection(&g_cs);
否则不安全
luciferisnotsatan 2011-09-21
  • 打赏
  • 举报
回复
    try
{
EnterCriticalSection(&g_cs);
g_map_deviceid.insert(map <long, string>::value_type(call_id, p_deviceid));
LeaveCriticalSection(&g_cs);
}
catch(...)
{ //如果跑了异常,那么就没LeaveCriticalSection了
return ;
}
liveeng 2011-09-21
  • 打赏
  • 举报
回复

strcpy( p_deviceid, it->second.c_str() );


溢出了
wyfwx 2011-09-21
  • 打赏
  • 举报
回复
没有泄露
赵4老师 2011-09-21
  • 打赏
  • 举报
回复
服务器程序不用scanf用fgets,不用strcpy用strncpy,不用sprintf用_snprintf

64,642

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧