1

总结:非常感谢大家!下面发布的所有回复都是正确的。最初的错误是我忘记为 NULL 终止符留出空间。strcpy() 是一个危险的函数,因为当我使用它时,它不知道“字符串”的结尾是什么时候。因此,strcpy() 抓取了大量数据并覆盖了返回地址。

编辑:从程序中添加了更多代码

已解决:老实说,我最初的实现是垃圾。如果我想交换数组的元素,我什至不知道为什么要这样写交换。(当时,每个元素中只有一个 char 数组。所以我能够摆脱旧的实现)。我已将其重写为:

void swap(ArrayElement list[], int index1, int index2) {
     ArrayElement temp;
     temp = list[index1];
     list[index1] = list[index2];
     list[index2] = temp;
}

我在以下函数结束时遇到分段错误问题。

struct ArrayElement {
    char data[SIZE_OF_ELEMENT];
    // Implemented this way so that I can expand to multiple values later on
}

//In main:
ArrayElement* list = new ArrayElement[NUM_OF_ELEMENTS];

void swap(ArrayElement list[], int index1, int index2) {
     char temp[SIZE_OF_ELEMENT];
     strcpy(temp, list[index2].data);
     strcpy(list[index2].data, list[index1].data);
     strcpy(list[index1].data, temp);
}

错误是第 45 行的分段错误,这是函数的结束大括号。这是使用 g++ 编译的。我使用 gbd 尝试调试它,一切正常,直到它碰到花括号。

如果需要,我可以从程序中提供更多代码。我不想发布整个内容,因为这是针对课程的。

4

3 回答 3

5

我最好的猜测是,字符串list[index2].data大于temp[]并且通过复制,您覆盖了堆栈和返回地址。

尝试插入长度测试:

#include <iostream>

...
int n = strlen(list[index2].data);
std::cerr << "len=" << n << ", SIZE_OF_ELEMENT=" << SIZE_OF_ELEMENT << std::endl;

看看,如果n(list[index2].data) 大于SIZE_OF_ELEMENT

于 2012-10-25T20:44:02.870 回答
2

strcpy是一个危险的功能。如果输入字符串的长度大于SIZE_OF_ELEMENT或等于,您将写入temp数组末尾。如果您必须使用一个固定大小的数组作为 中的输出数组,您应该在使用该函数之前strcpy测试它是否可以工作。strcpy

更好的是从使用char数组切换到std::string.

于 2012-10-25T20:52:01.830 回答
1

数据是这样定义的char data[SOME_CONSTANT]吗?如果是这样,那么您确定 SIZE_OF_ELEMENT 足够大吗?你也记得 NULL 终止符,对吧

如果在 ArrayElement 中的数据是这样定义的char *data;,并在稍后使用 malloc 分配,那么您确定index1 有一个足够大的缓冲区来容纳 index2 中的数据,反之亦然?同样,您也记住了 NULL 终止符,吗?

于 2012-10-25T20:54:38.000 回答