【问题标题】:Copying a string from static memory to dynamic memory fails [duplicate]将字符串从静态内存复制到动态内存失败[重复]
【发布时间】:2024-05-18 02:00:01
【问题描述】:

我构建了一个从用户那里获取字符串输入的函数。 然后它分配内存,但在 3 次输入后程序崩溃。

void friendNamesInput(int friendNum, char **ppFriendName) {
    char name[50] = { 0 }; //name 
    char *byteReALL = 0; //allocate bytes
    int i = 0;
    for (i = 0; i < friendNum; i++)
    {
        printf("Enter name of friend %d:", i + 1);
        fgets(name, 50, stdin); //input 50
        byteReALL = (char*)malloc(sizeof(char)*strlen(name)); //allcate nedded mem
        strncpy(byteReALL, name,50); //copy string data
        ppFriendName[i] = byteReALL; //address to array of arrays

    }
}

【问题讨论】:

标签: c arrays string memory malloc


【解决方案1】:

您没有为要复制的字符串分配足够的内存:

byteReALL = (char*)malloc(sizeof(char)*strlen(name));

C 中的字符串以 null 结尾,因此您需要为该字符添加 1 个额外字节。另外,sizeof(char) 被定义为 1,所以不需要相乘:

byteReALL = malloc(strlen(name) + 1);

一种更好的方法是使用strdup,它为字符串分配空间并一步将其复制到新分配的缓冲区:

printf("Enter name of friend %d:", i + 1);
fgets(name, 50, stdin);
ppFriendName[i] = strdup(name);

【讨论】: