Why it stops and finished with exit code 11?

前端 未结 2 570
后悔当初
后悔当初 2021-01-23 07:31

I don\'t know why it stops there and finished with exit code 11. It suppose to run until I give the command.

#include 
#include 
#i         


        
2条回答
  •  一整个雨季
    2021-01-23 08:05

    The problem is this part right here:

    void record(string name, string phoneNum, int count){
        string Name[] = {};
        string PhoneNum[] = {};
        Name[count] = {name};
        PhoneNum[count] = {phoneNum};
    
        //...
    }
    

    That's bad in C++ because string Name[] = {}; and others like it don't do what you think they do. They create an empty array of strings. Since variable length arrays are not a thing in C++, this creates a buffer overflow, which is undefined behavior. That's bad.

    Use a std::vector instead:

    void record(string name, string phoneNum){
        std::vector Name;
        std::vector PhoneNum;
        Name.push_back(name);
        PhoneNum.push_back(phoneNum);
    
        //...
    }
    
    

    P.S. There is another bug in your program. That is, Name and PhoneNum will get destroyed when the function exits each time. If that is intended, then fine. If you wish to keep a running list of records, that is bad. You can use a static variable to fix this:

    void record(string name, string phoneNum){
        static std::vector Name;
        static std::vector PhoneNum;
        //...
    }
    
    

提交回复
热议问题