c++ - 传递参数并给它们赋值会导致运行时错误

标签 c++ segmentation-fault runtime-error

所以我有以下代码:

void emptyString(char* token, int size) {
    for (int i=0; i < size; i++) token[i] = '\0';
}

    void setDefaults(char uloginName[], char *home_directory, char *password, char *shell, char *gecos) {
        emptyString(home_directory, sizeof(home_directory) - 1);
        strcat(home_directory, "home/home/");
        strcat(home_directory, uloginName);
    }

    int main(){
        char buffer[256];
        AccountInfo *tempAccount;
        UserDB users;
        char uloginName[9] = "Smith";
        char homeDirectory[33];
        int userID;
        int groupID;
        char password[17];
        char shell[17];
        char gecos[65];
        int i, j, k;
        char flag[3];
        char IDString[6];
        char command[11];
        char blank = ' ';

    setDefaults(uloginName, homeDirectory, password, shell, gecos);
    return 0;
    }

当我在 Visual Studio 中运行这段代码时,我会看到一个弹出窗口,上面写着

Run-Time Check Failure #2 - Stack around the variable 'users' was corrupted

这是由于 setDefaults() 方法中的代码行引起的。我希望有人帮助我更正代码。我的意图是将 home_directory 的值设置为“home/home/userloginname”,其中 userloginname 也是要传递的变量之一。

编辑:我刚刚发现我代码中的问题是 strcat() 方法。如果我对第一个使用 strcpy(),它工作正常,但是一旦我想添加更多,它会显示一个弹出窗口,说变量 users 得到了损坏。这是 userDB 类的代码:

class UserDB
{
private:
    AccountInfo* _accounts[200]; // store up to 200 accounts
    unsigned int _size; // number of account stored
    unsigned int _nextUid; // next user id to be assigned
    unsigned int _defaultGid; // default group id
    // other private methods necessary for this class
public:
    // constructors(empty), destructor
    void adduser( AccountInfo* newUser);
    void    showUsers();
    void    showPasswd();
    void    finger(char* userLoginName);class
    int size(); // return the number of accounts stored (_size)
    // and other public methods (mutators/setters, accessors/getters)
};

代码就在这里。也许我需要创建构造函数或析构函数或诸如此类的东西,但作为新手,我无法知道究竟是什么导致了错误并需要修复。

编辑:所以过了很长一段时间后,我发现 strcat() 是导致错误的原因,但是我需要做 strcat 声称要做的事情。这是我的完整代码的拷贝 http://ideone.com/A5iWh这样任何有兴趣的人都可以让我知道要更改什么,因为我不知道还能做什么。谢谢。

最佳答案

emptyString(home_directory, sizeof(home_directory) - 1);

你这里有n个问题:

sizeof(home_directory)

此语句为您提供指针 home_directory 的大小,而不是数组。
如果你想要函数内部数组的大小,那么你必须将它显式地作为函数参数传递。

此外,您的变量未初始化导致未定义的行为。
具体来说,在 uloginName 所示的代码片段中。
您将需要初始化所有变量,以免它们导致整个项目出现问题。

关于c++ - 传递参数并给它们赋值会导致运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9091609/

相关文章:

c++ - 使用 std::sort 对类 vector 进行降序排序

c++ - 如何调试并进入编译为C++的自定义语言源?

c++ - 有效地杀死一个windows进程

c - 字符串分配段错误 - 为什么会发生这种情况?

通过 ctypes 使用 pcap 的 python 段错误

fortran - 为什么在明确写入数组边界时没有运行时错误?

qt - Qt找不到dll,尽管一切都已设置

c++ - 如何分配子类的方法成员指针?

c - 段错误 malloc 指针函数

c++ sizeof在以下位置给出错误未处理的异常