簡體   English   中英

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 個項目之前, filledIndex3 < 4 ( capacityIndex )。 這導致arrPtr[4]被訪問(越界訪問,因為它的范圍當前是 [0..3])。

通過最初將filledIndex設置為0並更改arrPtr[++filledIndex] = n;來修復它arrPtr[++filledIndex] = n; arrPtr[filledIndex++] = n;

您應該注意到您的代碼存在嚴重缺陷:內存泄漏、可疑的名稱和樣式等。您可能希望將其修復版本發布到https://codereview.stackexchange.com/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM