0

我正在处理一项任务,并且在以下代码中不断出现分段错误main,我们不允许更改:

char signal[61];

Seti t2A(data, rF, rA, rB); // call constructor

t2A.getMessage(signal);            // calling member functions
t2A.getRanges(&pA, &pB);

usrF = t2A.getFrequency( );

if(strcmp(signal, correct)) { // <-- this is where i get segmentation fault.

类的实现Seti

class Seti {
    char signal[61];
    int freq;
    int a, b;
public:
    Seti(const char [ ], int, int, int);
    Seti();
    int getFrequency( );
    void getRanges(int *, int *);
    void setRanges(int , int );
    void getMessage(char *);
    bool replaceChar(int , char );
    bool copyPrimes(char *);
    bool copyFibonacci(char *);
    int initCap( );
    friend Seti join(Seti, Seti);
};

并执行getMessage

 void Seti::getMessage(char *pSignal) {
 strcpy (pSignal, signal);
 return;
 }

为什么在 main 中的 if 语句之后我会收到分段错误?

4

1 回答 1

1

从该代码中,Seti::signal可能未初始化,因此未正确以空值终止,并strcpy损坏内存,这会导致未定义的行为,幸运的是,这是段错误。

使用strncpy(记得'\0'自己在最后一个数组索引处添加终止字符)或snprintf代替strcpy, 也strncmp代替strcmp.

编辑:啊,correct根据您的评论,NULL 毕竟也是如此(而不是“NON-SEQUITOR”)。嗯,有你的问题。可能是您有两个具有该名称的变量而不是一个(常见的初学者错误)?

以上关于使用允许指定缓冲区大小的函数的建议仍然有效。

因评论而编辑:包装strncpy成这样的功能很有用,以避免错误:

char *strncpy0(char *dst, const char *src, size_t n) {
  dst[n-1] = 0;
  return strncpy(dst, src, n-1);
}
于 2013-03-01T20:57:25.880 回答