[英]C/C++ Memory Leak (Using PCRE)
// Returns a list of topic numbers found on the page
vector<string> findTopics(char* rData, int rDataLen) {
pcre *re;
const char *error;
int erroffset;
re = pcre_compile(
"topic/([0-9]+)", /* the pattern */
0, /* default options */
&error, /* for error message */
&erroffset, /* for error offset */
NULL); /* use default character tables */
if(re == NULL) {
printf("Couldn't compile regex (%s)", error);
// exit(-1):
}
int regOf[2];
vector<string> topics;
char *topic;
int offset = 0;
int rc = 1;
// Basically a preg_match_all()
while(true) {
rc = pcre_exec(re, NULL, rData, rDataLen, offset, 0, regOf, sizeof(regOf));
if (rc < 2) {
break;
}
topic = new char[8];
sprintf(topic, "%.*s\n", regOf[2*1+1] - regOf[2*1], rData + regOf[2*1]);
topics.push_back(topic);
offset = regOf[1];
}
pcre_free(re);
return topics;
}
This function is supposed to fetch a list of "topics" (matching topic/[0-9]+
) found in something specific that I parse to it, in the rData
, and it almost works. 这个函数应该在rData
获取一个“主题”列表(匹配topic/[0-9]+
),这些topic/[0-9]+
在我解析给它的特定内容中rData
,它几乎可以正常工作。 topics
gets filled with the topic numbers that it's supposed to. topics
充满了它应该的主题编号。
When I debug it in Visual Studio, I get this error messages straight after the end of the function (the return): Run-Time Check Failure #2 - Stack around the variable 'regOf' was corrupted. 当我在Visual Studio中调试它时,我在函数结束后直接收到此错误消息(返回): 运行时检查失败#2 - 变量'regOf'周围的堆栈已损坏。
I can't figure out what I'm doing wrong, and wondering if maybe somebody can point me in the right direction. 我无法弄清楚我做错了什么,并想知道是否有人可以指出我正确的方向。
You define regOf with 2 elements. 您可以使用2个元素定义regOf。 You then pass sizeof(regOf) into the pcre_exec function, however the function asks how many items are in the array, not how many bytes in size it is. 然后将sizeof(regOf)传递给pcre_exec函数,但该函数会询问数组中有多少项,而不是它的大小字节数。 As such, the function thinks it has 8 slots to fill, it only has 2, so can run off the end of the array and corrupt memory. 因此,该函数认为它有8个插槽填充,它只有2个,所以可以运行数组的末尾并破坏内存。
此外,对于其他答案,如果pcre_compile
和pcre_free
之间的任何语句抛出异常(我看到其中至少有三个可以这样做),则会泄漏内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.