C++;:分段错误,malloc.c:没有这样的文件或目录 我正在解决C++编程,需要检查所有9个!3x3矩阵的置换 1 2 3 4 5 6 7 8 9
我认为,我已经编写了正确的逻辑,并且实际上在2x2矩阵上对其进行了测试(当然,通过从3x3调整2x2的代码),从而得到正确的输出。但是,当我为实际约束运行程序时(即3x3matirx),程序会以分段错误终止。奇怪的是,当用GDB去毛刺时,它会打印出来C++;:分段错误,malloc.c:没有这样的文件或目录 我正在解决C++编程,需要检查所有9个!3x3矩阵的置换 1 2 3 4 5 6 7 8 9,c++,malloc,segmentation-fault,C++,Malloc,Segmentation Fault,我认为,我已经编写了正确的逻辑,并且实际上在2x2矩阵上对其进行了测试(当然,通过从3x3调整2x2的代码),从而得到正确的输出。但是,当我为实际约束运行程序时(即3x3matirx),程序会以分段错误终止。奇怪的是,当用GDB去毛刺时,它会打印出来 Program received signal SIGSEGV, Segmentation fault. 0x00007ffff74f6bbc in _int_malloc (av=av@entry=0x7ffff7839b20 <main_
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff74f6bbc in _int_malloc (av=av@entry=0x7ffff7839b20 <main_arena>,
bytes=bytes@entry=12) at malloc.c:3353
3353 malloc.c: No such file or directory.
程序本应输出
6
,但会产生SIGSEGV
,如前所述。我做错了什么?尝试使用调试打印行来查看分段错误发生的位置。另外,尝试将矩阵存储为9个元素的数组,而不是矩阵。请不要在此处发布的代码中使用“`”。这不是标准。试着精简程序。目标是。请不要发布需要潜在助手通过cin
输入值的程序。使程序自包含。在打开所有警告的情况下编译,并修复代码以删除它们。有趣的谜题。这个程序会在无限循环中继续交换7和4吗?问题很好,忽略那些反对者。但是你应该试着自己调试它。例如,当您看到segfault等时,在GDB中执行堆栈跟踪
#include <bits/stdc++.h>
using namespace std;
int min_count;
map<string, bool> mp;
vector<vector<int>>vec(3, vector<int>(3, 0));
// n <= 17
bool isPrime(int n) {
return n == 2 or n == 3 or n == 5 or n == 7 or n == 11 or n == 13 or n == 17;
}
// get a String representation of the matrix vec
string getStringRepresentation(vector<vector<int>> vec) {
string str = "";
for(auto i : vec) {
for(auto j : i)
str += ('0' + j);
}
return str;
}
void printRecursive(vector<vector<int>> &vec, map<string, bool> &mp, int count) {
string str = getStringRepresentation(vec);
if(str == "123456789" and count <= min_count)
min_count = count;
//cout << str << " " << count << endl;
if(mp[str])
return;
mp[str] = true;
for(int i = 0; i < vec.size(); ++i) {
for(int j = 0; j < vec[i].size(); ++j) {
if(j != vec[i].size() - 1 and isPrime(vec[i][j] + vec[i][j+1])) {
swap(vec[i][j], vec[i][j+1]);
printRecursive(vec, mp, count + 1);
swap(vec[i][j], vec[i][j+1]);
}
if(i != vec.size() - 1 and isPrime(vec[i][j] + vec[i+1][j])) {
swap(vec[i][j], vec[i+1][j]);
printRecursive(vec, mp, count + 1);
swap(vec[i][j], vec[i+1][j]);
}
}
}
}
// solve for each test case
void solve() {
for(auto &i : vec) {
for(auto &j : i) {
cin >> j;
}
}
//cout << getStringRepresentation(vec) << endl;
min_count = INT_MAX;
printRecursive(vec, mp, 0); // recursively examine all possible states.
// if min_count is not changed(i.e. reamains equal to INT_MAX then the required state is unreachable, print -1 to indicate)
cout << (min_count == INT_MAX ? -1 : min_count) << endl;
}
int main() {
int test; // test are the number of test cases, each will invoke the solve() function.
cin >> test;
while(test--)
solve();
}
1
7 3 2
4 1 5
6 8 9