【问题标题】:Segmentation fault (core dumped) with the strcpy-function in cc 中 strcpy 函数的分段错误(核心转储)
【发布时间】:2017-11-15 10:13:20
【问题描述】:

我正在尝试编写一个函数,它将读取两个字符串 stringArray[MAX]="ABADDFDEFBFCCHCGGEHJJI" 和 popArr[MAX]="ABCDEFGHIJ" 并生成如下输出:

A
B-F-D-A
C-F-D-A
D-A
E-G-C-F-D-A
F-D-A
G-C-F-D-A
H-C-F-D-A
I-J-H-C-F-D-A
J-H-C-F-D-A

但是我收到了Segmentation fault (core dumped) 错误。为什么?这是我的代码:

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>

#define MAX 100

size_t strlstchar(const char *str, const char ch)
{
    char *chptr = strrchr(str, ch);
    return chptr - str;
}

int main(){ 
    // Input strings    
    char stringArray[MAX]="ABADDFDEFBFCCHCGGEHJJI";
    char popArr[MAX]="ABCDEFGHIJ";

    int index=2, lenpop, lentemp;
    char usedString[MAX]="";    
    char tempChar;

    lenpop    = strlen(popArr); 

    printf("%c\n", stringArray[0]); 

    for(int i=1;i<lenpop;i++){
        strcpy(usedString, stringArray);
        printf("%c", popArr[i]);
        tempChar = popArr[i];

        while(tempChar!=stringArray[0]){
            while(index%2==0){
                index = strlstchar(usedString, tempChar);
                lentemp = strlen(usedString);
                usedString[lentemp-index-1]=0;
                }   

            printf("-%c", usedString[index-1]);
            tempChar=usedString[index-1];   
            index=2;        
            }
            printf("\n");       
        }

    return 0;
    }

提前致谢!

【问题讨论】:

  • 问题陈述是什么?很难猜测输出如何依赖于输入。
  • 调试器会告诉你段错误发生在哪里。您的问题陈述含糊不清。 stringArray 似乎描述了图形的边缘,您的输出应该是 A 的路径。请将其编辑到问题中。
  • 如果用strcat替换strcpy,segfault还会出现吗?
  • 你将不得不解释输入应该如何给出输出。
  • 忽略算法!我改变了问题,只询问发生的错误。

标签: c algorithm strcpy


【解决方案1】:

分段违规发生在这一行:

    usedString[lentemp - index - 1] = 0;

在这里,您尝试从末尾查找索引,但您的 strlstchar 从开头返回索引,尽管它从末尾开始搜索。当然,您希望在找到的字符处截断字符串。

将这一行替换为:

    usedString[index] = 0;

你会得到想要的输出。

【讨论】:

  • 感谢它在第一次迭代B-F-D-A 中工作,但之后错误再次出现。
  • 嗯。我无法重现那个。不管怎样,你似乎找到了解决办法。
  • 我在 ubuntu 16.04 上使用 gcc -Wall -O3 -DNDEBUG -static -std=c99 -pipe -o "%e" "%f" -lm 编译
  • 如果我从您的问题中获取代码,只需按照上面显示的内容进行编译,然后编译即可。我看不出将内存放在堆上如何解决问题。 (你永远不会从malloc 或strdup 释放内存,所以你有很多内存泄漏。)我也不确定你为什么要为一个简单的程序激活大量优化。
猜你喜欢
  • 2015-08-10
  • 2014-04-30
  • 1970-01-01
  • 1970-01-01
  • 2020-12-08
  • 2022-01-14
  • 2017-02-25
  • 2016-07-12
  • 2018-03-16
相关资源
最近更新 更多