// 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. topics
gets filled with the topic numbers that it's supposed to.
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.
I can't figure out what I'm doing wrong, and wondering if maybe som开发者_Go百科ebody can point me in the right direction.
You define regOf with 2 elements. 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. 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.
Furthermore to the other answers, if any of your statements between pcre_compile
and pcre_free
throw an exception (I see at least three of them that could do so), you leak memory.
精彩评论