簡體   English   中英

C++ 對象分段錯誤(核心轉儲)錯誤

[英]C++ Object Segmentation Fault (core dumped) Error

我是 C++ 的新手,所以請放輕松,所以我有以下課程:

class DATA
{
    private:
        char* Name;
        char* Address;
        int Id;
        void initData(int size=200)
        {
            (this->Name)=(char*)malloc(sizeof(char)*size);
            (this->Address)=(char*)malloc(sizeof(char)*size);
        }
    public:
        void readData(void)
        {
            this->initData();
            printf("Enter Name: "); scanf("%s\n",this->Name);
            printf("Enter Address: "); scanf("%s\n",this->Address);
            printf("Enter Id: "); scanf("%d\n",&(this->Name));
        }
        void printData(void)
        {
            printf("Name: %s",this->Name);
            printf("Address: %s",this->Address);
            printf("Id: %d",this->Id);
        }
};

但是當我初始化一個對象然后調用公共方法時,會發生以下情況:

Enter Name: John Doe
Enter Address: 53 Olive, St.
Segmentation fault (core dumped)

所以,如果有人能告訴我為什么(我知道什么是分段錯誤,但不明白為什么會出現在這里)。

在方法readData

     printf("Enter Id: "); scanf("%d\n",&(this->Name));

您應該讀取一個整數的讀取Id ,但讀取字符串this->Name 任何一個

scanf("%d\n",&(this->Id));

當您使用 C++ 時,使用cincout比 C 風格的scanfprintf更方便、更容易遇到這些問題。

cin >> Id;

在編寫 C++ 代碼時,不要使用char*malloc 至少使用new甚至更好地使用std::string ,它也適用於std::cinstd::cout 您的示例會泄漏內存,因為您永遠不會釋放 Name 和 Address。

分段錯誤是由scanf("%d\\n",&(this->Name)) ,正如已經指出的那樣,它應該是&(this->Id)

暫無
暫無

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

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