【发布时间】:2015-12-04 20:41:27
【问题描述】:
我正在 C 中为一阶逻辑公式实现解析器。要检查二进制连接公式(即格式为 (A BinaryConnective B)),我需要拆分字符串并检查 A 和 B 是否为公式。我使用 subString 函数完成了这项工作,并从 partone 和 parttwo(分别为 A 和 B)调用它:
char *partone(char *g) {
//Given the formula (A*B) this returns A
return subString(g, 1, binPosition(g));
}
char *parttwo(char *g) {
//Given the formula (A*B) this returns B
return subString(g, binPosition(g) + 1, strlen(g) - 1);
}
子串函数如下:
char *subString(char *g, int start, int end) {
//the substring includes index start but does not include the end index.
char *substr = malloc(sizeof(char)*(end - start));
int i;
for(i = 0; i < (end - start); i++) {
substr[i] = g[start + i];
}
return substr;
}
当我传递除否定公式以外的任何函数时,这都有效(我们使用字符“-”表示否定)。例如,当我通过 (-X[xz]>X[yz]) 时,程序返回“不是公式”,但如果我在没有否定的情况下编写相同的内容,它会完美运行。问题是 partone() 返回的 substr 是“-X[xz]$”,其中 $ 可以是我认为之前存储在内存中的任何随机字符。任何想法为什么只在这种情况下发生这种情况?我是 C 新手,我到处都看过。
提前致谢。
【问题讨论】:
-
C 中的字符串需要 NUL 终止。您的
subString函数不是 NUL 终止的,因此没有返回有效的 C 字符串。如果这不是问题,请提供Minimal Complete and Verifiable Example。 -
.. 并且需要一个额外的内存字节来容纳它。
-
如果
end是你需要的最后一个字符索引malloc(end - start + 2) -
... 和
sizeof char始终为 1.. 并且应始终检查malloc... 和strlen(g) - 1的返回值可能会给您一个负数。
标签: c string parsing logic substring