这是我对C和正则表达式的第一次真正的尝试所以请耐心等待...我有一个模式数组(shortener_patterns),我将其传递给compile_patterns
以及编译模式的计数和数组(shortener_r_patterns) )。我能够编译模式,但代码将在regexec
上进行段错误。我猜这与我引用shortener_r_patterns
的方式有关,而且我还没有完全理解指针。或者也许他们首先没有正确编译。有人能让我朝着正确的方向前进吗?
char **shortener_patterns = '\0';
regex_t **shortener_r_patterns;
int *shortener_count = 0;
int compile_patterns(char **patterns, regex_t **r_patterns, int *count, int *compiled_count) {
static int i;
if (!(r_patterns = calloc(count, sizeof(regex_t)))) {
return -1;
}
for (i=0; i<count; i++) {
log(5, "compiling pattern %i: %s\n", i, patterns[i]);
if (regcomp(&(r_patterns[i]), patterns[i], REG_EXTENDED|REG_NEWLINE|REG_ICASE|REG_NOSUB) != 0) {
log(1, "invalid pattern: %s\n", patterns[i]);
return -1;
}
// increment the compiled count
(*compiled_count)++;
}
log(3, "finished compiling %i\n", count);
return 0;
}
int check_shortener(char *domain) {
static int i;
if (!shortener_count) {
return 0;
}
for (i=0; i<shortener_count; i++) {
log(5, "checking shortner pattern '%s' against %s:%d\n", shortener_patterns[i], domain, i);
if (regexec(&(shortener_r_patterns[i]), domain, 0, 0, 0) == 0) {
log(1, "pattern %i '%s' found in %s\n", i, shortener_patterns[i], domain);
return 1;
}
}
return 0;
}
这是我扫描文件以获取模式内容,添加到数组然后最终编译模式数组的地方。
- 剪辑 -
while ((rc = fscanf(f, "%254[^\n]", buf)) > 0) {
if (buf[0] == '#') {
fscanf(f, "\n");
continue;
}
newshortener = realloc(shortener_patterns, sizeof(char *) *(count+1));
if (newshortener) {
shortener_patterns = newshortener;
}
else {
log(0, "could not realloc memory for shortener patterns\n");
fclose(f);
return -1;
}
shortener_patterns[count++] = strdup(buf);
fscanf(f, "\n");
}
fclose(f);
if (compile_patterns(shortener_patterns, shortener_r_patterns, count, &shortener_count) > 0) {
log(0, "Failed to compile %s patterns\n", sfile);
}
- 剪辑 -
答案 0 :(得分:1)
shortener_count
没有任何空格,您已将其定义为int *
,然后将指针设置为0,然后您访问指针。