c - 算法正确但实现错误?

标签 c arrays algorithm segmentation-fault

我是 C 初学者,有一些 python 和 java 经验。我想用 C 解决一个问题。问题是这样的:

将输入作为句子,单词仅由空格分隔(假设仅小写),按照以下规则重写句子:

1)如果某个单词第一次出现,请保持不变。

2) 如果该单词出现两次,则将第二次出现的单词替换为被复制两次的单词(例如,two -->twotwo)。

3) 如果该单词出现三次或以上,则删除第二次之后出现的所有内容。

将输出打印为句子。输入句子和每个单词的最大长度分别为 500 个字符和 50 个字符。

示例输入:叮当叮当叮当一路叮当

示例输出:叮当铃叮当叮叮铃铃响一路

我采取的方法是:

1)读取输入,分离每个单词并将它们放入一个字符指针数组中。

2) 使用嵌套的 for 循环来遍历数组。对于第一个单词之后的每个单词:

 A - If there is no word before it that is equal to it, nothing happens.

 B - If there is already one word before it that is equal to it, change the word as its "doubled form".

 C - If there is already a "doubled form" of itself that exists before it, delete the word (set the element to NULL.

3) 打印修改后的数组。

我对这种方法的正确性相当有信心。然而,当我实际编写代码时:

'''

int main()
{

    char input[500];

    char *output[500];


    // Gets the input
    printf("Enter a string: ");
    gets(input);

    // Gets the first token, put it in the array
    char *token = strtok(input, " ");
    output[0] = token;

    // Keeps getting tokens and filling the array, untill no blank space is found
    int i = 1;
    while (token != NULL) {
        token = strtok(NULL, " ");
        output[i] = token;
        i++;
    }


    // Processes the array, starting from the second element
    int j, k;
    char *doubled;
    for (j = 1; j < 500; j++) {
        strcpy(doubled, output[j]);      
        strcat(doubled, doubled);        // Create the "doubled form"
        for (k = 0; k < j; k++) {
            if (strcmp(output[k], output[j]) == 0) {     // Situation B
                output[j] = doubled;
            }
            if (strcmp(output[k], doubled) == 0) {       // Situation C
                output[j] = ' ';
            }
        }
    }


    // Convert the array to a string
    char *result = output[0];          // Initialize a string with the first element in the array     
    int l;
    char *blank_space = " ";           // The blank spaces that need to be addded into the sentence
    for (l = 1; l < 500; l++) {
        if (output[l] != '\0'){        // If there is a word that exists at the given index, add it
            strcat(result, blank_space);
            strcat(result, output[l]);

        }
        else {                         // If reaches the end of the sentence
            break;
        }
    }

    // Prints out the result string
    printf("%s", result);

    return 0;
}

'''

我对每个单独的 block 进行了一系列测试。有几个问题:

1)在处理数组时,循环中的strcmp、strcat和strcpy似乎给出了Segmentation failure错误报告。

2)打印数组时,单词没有显示它们应该执行的顺序。

我现在很沮丧,因为似乎这些问题都来 self 的代码的一些内部结构缺陷,并且它们与我不太熟悉的 C 的内存机制有很大关系。我该如何解决这个问题?

最佳答案

有一个问题引起了我的注意。这段代码是错误的:

char *doubled;
for (j = 1; j < 500; j++) {
    strcpy(doubled, output[j]);      
    strcat(doubled, doubled);        // Create the "doubled form"

doubled不指向任何实际内存。因此,尝试将数据复制到它指向的位置是未定义的行为,并且几乎肯定会导致 SIGSEGV - 如果它不导致SIGSEGV,它就会损坏内存.

这需要修复 - 您无法使用 strcpy() 复制字符串或strcat()指向不指向实际内存的指针。

这会更好,但仍然不理想,因为没有进行检查来确保没有缓冲区溢出:

char doubled[ 2000 ];
for (j = 1; j < 500; j++) {
    strcpy(doubled, output[j]);      
    strcat(doubled, doubled);        // Create the "doubled form"

这也是 doubled 的问题定义如下:

        if (strcmp(output[k], output[j]) == 0) {     // Situation B
            output[j] = doubled;
        }

这只是点output[j]doubled 。下一个循环迭代将覆盖 doubled ,以及 output[j] 的数据仍然指向 to 将被更改。

这可以解决这个问题:

        if (strcmp(output[k], output[j]) == 0) {     // Situation B
            output[j] = strdup( doubled );
        }

strdup()是一个 POSIX 函数,毫不奇怪,它会复制一个字符串。该字符串需要是 free()不过,稍后,如 strdup()等同于:

char *strdup( const char *input )
{
    char *duplicate = malloc( 1 + strlen( input ) );
    strcpy( duplicate, input );
    return( duplicate );
}

正如所指出的,strcat(doubled, doubled);也是一个问题。一种可能的解决方案:

    memmove(doubled + strlen( doubled ), doubled, 1 + strlen( doubled ) );       

复制 doubled 的内容字符串到从原始'\0'开始的内存终结者。请注意,由于原来的 '\0'终止符是字符串的一部分,不能使用 strcpy( doubled + strlen( doubled ), doubled ); 。您也不能使用 memcpy() ,出于同样的原因。

关于c - 算法正确但实现错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58692988/

相关文章:

c - 如何从任务管理器中的 "Applications"选项卡隐藏窗口?

android - 将自定义对象数组保存到共享首选项

algorithm - 支持记分牌最佳操作的数据结构

java - 基于 Parens 将字符串拆分为更小的部分

javascript - 最佳小便池策略

c - mingW 中的标准 C 库

c - linux终端: Changing images: printing over already printed text游戏

c - 如何使用 SSE-intrinsics 优化 C 代码以实现打包的 32x32 => 64 位乘法,并将这些结果的一半解包为(Galois Fields)

php - : in_array or array_unique? 用什么比较好

java - Go 中的 Java Arrays.copyOfRange 等价于什么?