簡體   English   中英

分段故障(核心已轉儲)4

[英]Segmentation fault (core dumped) 4

使用Ctrl + D停止程序輸入后,我不斷收到錯誤Segmentation Fault(core dumped)。 我一直在搜索該錯誤並試圖找出導致該錯誤的原因,但我似乎無法找出原因。 我曾嘗試使用Google搜索該問題,並瀏覽了該網站上的其他問題/答案,但仍然無法弄清楚為什么會出現此錯誤。 從我的研究中,我發現分段錯誤錯誤是由於嘗試訪問我無權訪問的內存而引起的。 我希望這是對的。

我對C ++相當陌生,希望您能為我提供任何幫助。

#include <iostream>
using namespace std;

#include "video.h"

int main() {

    const int MAX = 100;
    Video *video[MAX];  // up to 100 videos

    for(int l = 0; l < MAX; l++)
    {
        video[l] = NULL;
    }

    string title;
    string url;
    string desc;
    string sorting;
    float length;
    int rate;

    cout << "What sorting method would you like to use?" << endl;
    getline(cin, sorting);
    cout << "Enter the title, the URL, a comment, the length, and a rating for each video" << endl;

    while(getline(cin, title))
    {
        getline(cin, url);
        getline(cin, desc);
        cin >> length;
        cin >> rate;
        cin.ignore();
        for(int k=0; k < MAX; k++)
        {
            video[k] = new Video(title, url, desc, length, rate);
        }
    }


    video[MAX]->print();  // prints the new Video object

    delete[] video[MAX];

    return 0;
}

您的代碼中有幾個問題:

1)錯誤使用delete[]

首先, delete[]僅應用於刪除動態分配的數組。 你的不是一個。

第二,即使視頻動態分配的數組,刪除它的正確方法是

delete[] video;

刪除代碼中視頻的正確方法是遍歷數組並刪除每個視頻:

for(int k=0; k < MAX; k++)
{
    delete video[k];
}

2)對數組最后一個元素的索引不正確。

video[MAX]->print();

應該

video[MAX-1]->print();

第一個元素的索引為零,第二個元素的索引為1 ...因此最后一個(MAX)元素的索引為MAX-1。

3)最后,雖然不是造成分段錯誤的原因,但您可能並不想每次讀取一行時都用相同的視頻填充整個數組。 但是,這就是代碼的作用:)

除了Danra已經指出的delete的錯誤用法之外,您的數組

Video *video[MAX];

沒有元素

video[MAX];

最后一個元素是

video[MAX-1];

因為C ++從0開始計數(就像您在for循環中正確執行的一樣)。 所以

video[MAX]->print(); 

將失敗。

delete[] video[MAX];

嘗試數組刪除超出視頻結尾的元素。

您的意思是:

delete video[MAX - 1];

否則你不是

delete[] video;

同樣,您可能需要查看

video[MAX]->print();  // prints the new Video object

這會嘗試打印第MAX + 1個視頻,而不是最后一個視頻或整個視頻列表。

您還應該查看以下循環:

    for(int k=0; k < MAX; k++)
    {
        video[k] = new Video(title, url, desc, length, rate);
    }

暫無
暫無

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

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