C++:分段错误(核心转储)
c++: segmentation fault (core dumped)
我正在尝试使用指针和模板在C++中实现动态数组,以便我可以接受所有类型的数组。代码在int
上运行良好,但使用string
会产生错误。我在网上尝试了其他SO问题,但对我的场景一无所获。
法典:
#include <iostream>
#include <string>
using namespace std;
template <typename T>
class dynamicIntArray
{
private:
T *arrPtr = new T[4]();
int filledIndex = -1;
int capacityIndex = 4;
public:
// Get the size of array
int size(void);
// Insert a data to array
bool insert(T n);
// Show the array
bool show(void);
};
template <typename T>
int dynamicIntArray<T>::size(void)
{
return capacityIndex + 1;
}
template <typename T>
bool dynamicIntArray<T>::insert(T n)
{
if (filledIndex < capacityIndex)
{
arrPtr[++filledIndex] = n;
return true;
}
else if (filledIndex == capacityIndex)
{
// Create new array of double size
capacityIndex *= 2;
T *newarrPtr = new T[capacityIndex]();
// Copy old array
for (int i = 0; i < capacityIndex; i++)
{
newarrPtr[i] = arrPtr[i];
}
// Add new data
newarrPtr[++filledIndex] = n;
arrPtr = newarrPtr;
return true;
}
else
{
cout << "ERROR";
}
return false;
}
template <typename T>
bool dynamicIntArray<T>::show(void)
{
cout << "Array elements are: ";
for (int i = 0; i <= filledIndex; i++)
{
cout << arrPtr[i] << " ";
}
cout << endl;
return true;
}
int main()
{
dynamicIntArray<string> myarray;
myarray.insert("A");
myarray.insert("Z");
myarray.insert("F");
myarray.insert("B");
myarray.insert("K");
myarray.insert("C");
cout << "Size of my array is: " << myarray.size() << endl;
myarray.show();
}
错误:
segmentaion fault (core dumped)
经典的逐一错误:
if (filledIndex < capacityIndex)
{
arrPtr[++filledIndex] = n;
在插入第 5 项之前,filledIndex
3
通过最初将filledIndex
设置为0
并将arrPtr[++filledIndex] = n;
更改为arrPtr[filledIndex++] = n;
来修复它
您应该注意,您的代码存在严重的缺陷:内存泄漏,可疑的名称和样式等。您可能希望将其固定版本发布到 https://codereview.stackexchange.com/。
相关文章:
- 如何找出GDB的SIGTRAP核心转储的根本原因
- C++映射分割错误(核心转储)
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 浮点异常(核心转储)#694457
- 分段错误(核心转储)但无法弄清楚
- 链接到libkcapi时没有核心转储
- 分段错误(核心转储) - 使用 SavedModel 的 Tensorflow C++ API 进行推断
- 在基数排序中,我得到 munmap_chunk():无效指针和中止(核心转储).为什么?
- C++指针无法在函数外部传递值和分段错误(核心转储)错误
- 合并排序:分段错误核心转储
- C++:分段错误(核心转储)
- 从 pybind11 构建导入模块时出现"分段错误(核心转储)"
- 如何使用 lldb 在曼扎罗中调试 lz4 文件格式的核心转储?
- qt C++命令行代码中的分段错误(核心转储)
- 从文件中读取的数据,但发生核心转储错误
- googletest:测试基类具有纯虚拟方法的派生类时的核心转储
- C++ atof - 分段错误(核心转储)
- Linux C 只禁止我的程序使用核心转储
- 为什么我的代码包含错误分段错误(核心转储)?