gpt4 book ai didi

c++ - C++:段错误(核心已转储)

转载 作者:行者123 更新时间:2023-12-01 15:05:22 25 4
gpt4 key购买 nike

我正在尝试使用指针和模板在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)

最佳答案

经典Off-by-one error:

if (filledIndex < capacityIndex)
{
arrPtr[++filledIndex] = n;

在插入第5个项目之前, filledIndex3 < 4( capacityIndex)。这导致 arrPtr[4]被访问(由于其范围当前为[0..3],因此超出了访问范围)。

通过最初将 filledIndex设置为 0并将 arrPtr[++filledIndex] = n;更改为 arrPtr[filledIndex++] = n;进行修复

您应该注意,您的代码虽然存在严重缺陷:内存泄漏,可疑的名称和样式等。您可能需要将其固定版本发布到 https://codereview.stackexchange.com/

关于c++ - C++:段错误(核心已转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59646592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com