【问题标题】:Right algorithm but wrong implementation?正确的算法但错误的实现?
【发布时间】:2020-02-29 17:50:47
【问题描述】:

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

将输入作为一个句子,单词之间只用空格隔开(只假设小写),按照以下规则改写句子:

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

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

3) 如果单词出现 3 次或更多,则删除第二次之后的所有出现。

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

示例输入:jingle bells jingle bells jingle all the way

示例输出:jingle bells jinglejingle bellsbells all the way

我采取的方法是:

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

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;
}

'''

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

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

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

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

【问题讨论】:

  • 永远不要永远使用gets!这是一个dangerous 函数,甚至已从 C 语言中删除。使用例如fgets 代替。
  • 至于您的问题,您确实需要退后几步,回到您的书籍、教程或课程中,阅读更多关于指针的信息。指针必须指向某个有效的位置,您才能使用它!您有许多未初始化(因此是不确定的)指针。
  • 是的,我在尝试运行程序时收到了这个警告,但是使用gets实际上是这个问题的要求之一,所以我认为无论如何我都应该遵循它。
  • 那么给你这个作业或练习的书或教程应该扔掉!如果是老师,你需要告诉他或她。除非这是关于缓冲区溢出及其危险的练习,否则永远不要使用gets,即使老师告诉你这样做。
  • 使用-Wall -Wextra 编译。他们会告诉你doubled 有什么问题

标签: c arrays algorithm segmentation-fault


【解决方案1】:

我突然想到一个问题。这段代码是错误的:

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。下一次循环迭代将覆盖doubledoutput[j] 仍指向的数据将发生变化。

这将解决这个问题:

        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()

【讨论】:

  • 感谢您的建议!我试图根据他们调整我的代码,但我仍然得到相同的分段错误错误(仅测试数组处理块)
  • 我不认为strcat(doubled, doubled);(或任何其他重叠的情况)是允许的。
  • @joop 真。我没抓到那个。
【解决方案2】:

您的代码通过写入尚未拥有的内存在多个位置调用 undefined behavior,这可能是您看到的 segmentation fault 的原因。例如,在这个片段中:

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]);

单独...

char *result = output[0]; //creates a pointer, but provides no memory.

...不足以接收诸如

之类的内容
strcat(result, blank_space);
 strcat(result, output[l]);  

它需要内存:

char *result = malloc(501);//or more space if needed.
if(result)
{
    //now use strcat or strcpy to add content

【讨论】:

  • 上次我检查时,calloc() 接受了两个参数。
  • @joop - 谢谢 - 我在想malloc,但习惯性地写了calloc。已编辑
猜你喜欢
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 2018-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多