Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/129.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用C9.io和C++;_C++_Compiler Errors - Fatal编程技术网

C++ 使用C9.io和C++;

C++ 使用C9.io和C++;,c++,compiler-errors,C++,Compiler Errors,我在使用c9编译器时遇到了一个堆栈崩溃错误,我查找了错误原因,可能是错误代码/传递变量或未声明/初始化的内容,但我在代码中找不到错误 我已经去除了以下代码中与错误无关的任何不必要的代码,这就是我所拥有的: #include <iostream> #include <cstring> using namespace std; void checkWord(char *word, int size); int main () { string word1 = "

我在使用c9编译器时遇到了一个堆栈崩溃错误,我查找了错误原因,可能是错误代码/传递变量或未声明/初始化的内容,但我在代码中找不到错误

我已经去除了以下代码中与错误无关的任何不必要的代码,这就是我所拥有的:

#include <iostream>
#include <cstring>

using namespace std;

void checkWord(char *word, int size);

int main () {
    string word1 = "racecar";
    char wordArr[sizeof(word1)];
    strcpy(wordArr, word1.c_str());
    checkWord(wordArr, strlen(wordArr));

    string word2 = "something";
    char word2Arr[sizeof(word2)];
    strcpy(word2Arr, word2.c_str());
    checkWord(word2Arr, strlen(word2Arr));
}

void checkWord(char *wordArr, int size) {
    // cout << "Size1: " << size << endl;
    int workingSize;
    if ((size % 2) != 0) {
        workingSize = (size +1)/2;
    } else {
        workingSize = size/2;
    }
    char *p, *q;
    p = wordArr;
    q = wordArr+strlen(wordArr)-1;
    bool pal = true;
    for (int i = 0; i < workingSize; i++) {
        if (*p != *q) {
            pal = false;
        }
        p++;
        q--;
    }
}

否则,程序执行时不会出现任何问题,在本例中,确认单词“racecar”和“something”是否为回文。

您声明
char-wordArr[sizeof(word1)]短一个字符。Sizeof给出了字符串中的字符数,但您需要为后面的
'\0'
多加一个字符

因此,您开始覆盖您不拥有的内存,超出此范围的任何内容都是随机的未定义行为。

sizeof(word1)
返回变量
word1
占用的字节数,它与所代表的字符串长度无关。您应该使用
word1.length()+1
获取字符串的长度,包括终止的nul字符。(与
sizeof(word2)
相同)


更好的解决方案是更改
checkWord
以将其第一个参数作为
const char*wordArr
,并使用
word1.c_str()
传入该单词,或者只需将字符串传递到
checkWord
,而不使用字符指针。

string
char*
的转换似乎没有必要。
*** stack smashing detected ***:/home/ubuntu/workspace/.c9/metadata/workspace/3_16Lab2.cpp.o terminated
bash: line 12: 48077 Aborted                 $file.o $args


Process exited with code: 134