我正在做一项作业,但我在 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 语句之后收到段错误?
最佳答案
从该代码来看,Seti::signal
可能未初始化,因此没有正确地以 null 终止,并且 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);
}
关于c++ - strcmp 和复制的 char 数据的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15166518/