【发布时间】:2019-11-09 18:06:29
【问题描述】:
我是 C 的新手,我创建了一个函数,可以从字符串中删除特殊字符并返回一个新字符串(没有特殊字符)。
乍一看,这似乎运行良好,我现在需要在一个(巨大的)文本文件(一百万个句子)的行上运行这个函数。在几千行/句子(大约 4,000 行)之后,我得到了一个段错误。
我在 C 语言中的内存分配和字符串方面没有太多经验,我试图找出我的代码的问题,不幸的是没有任何运气。 代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
char *preproccessString(char *str) {
// Create a new string of the size of the input string, so this might be bigger than needed but should never be too small
char *result = malloc(sizeof(str));
// Array of allowed chars with a 0 on the end to know when the end of the array is reached, I don't know if there is a more elegant way to do this
// Changed from array to string for sake of simplicity
char *allowedCharsArray = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// Initalize two integers
// i will be increased for every char in the string
int i = 0;
// j will be increased every time a new char is added to the result
int j = 0;
// Loop over the input string
while (str[i] != '\0') {
// l will be increased for every char in the allowed chars array
int l = 0;
// Loop over the chars in the allowed chars array
while (allowedCharsArray[l] != '\0') {
// If the char (From the input string) currently under consideration (index i) is present in the allowed chars array
if (allowedCharsArray[l] == toupper(str[i])) {
// Set char at index j of result string to uppercase version of char currently under consideration
result[j] = toupper(str[i]);
j++;
}
l++;
}
i++;
}
return result;
}
这是程序的其余部分,我认为问题可能在这里。
int main(int argc, char *argv[]) {
char const * const fileName = argv[1];
FILE *file = fopen(fileName, "r");
char line[256];
while (fgets(line, sizeof(line), file)) {
printf("%s\n", preproccessString(line));
}
fclose(file);
return 0;
}
【问题讨论】:
-
char *result应该分配到 str + 1char *result = malloc(strlen(str) + 1);的长度 -
@MichaelBianconi 这并没有解决问题,它仍然在同一位置给我一个段错误。
-
为什么不用像
tr这样的预写工具来做呢? -
你能不能逗我一下,在
result[j] = toupper(str[i])); j++;之后加一个break;? -
您没有向
result字符串添加空终止符。将result[i] = 0;放在return result;之前
标签: c string replace char segmentation-fault