c - malloc、sizeof 和 strlen 函数可能发生冲突吗?

标签 c malloc sizeof strlen

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

typedef struct _person
{
    char *fname;
    char *lname;
    bool isavailable;
}Person;


Person *getPersonInstance(void)
{
    Person *newPerson = (Person*) malloc(sizeof(Person));
    if(newPerson == NULL)
        return NULL;
    return newPerson;
}

void initializePerson(Person *person, char *fname, char *lname, bool isavailable)
{
    person->fname = (char*) malloc(strlen(fname)+1);
  /*problematic behaviour if i write: person->fname = (char*) malloc (sizeof(strlen(fname)+1)); */

    person->lname = (char*) malloc(strlen(lname)+1);
 /*problematic behaviour if i write: person->lname = (char*) malloc (sizeof(strlen(lname)+1)); */

    strcpy(person->fname,fname);
    strcpy(person->lname,lname);
    person->isavailable = isavailable;

    return;

}

// test code sample
int main(void)
{
    Person *p1 =getPersonInstance();
    if(p1 != NULL)
        initializePerson(p1, "Bronze", "Medal", 1);

    Person *p2 =getPersonInstance();
    if(p2 != NULL)
        initializePerson(p2, "Silver", "Medalion", 1);

    Person *p3 =getPersonInstance();
    if(p3 != NULL)
        initializePerson(p3, "Golden", "Section", 1);

    printf("item1=> %10s, %10s, %4u\n",p1->fname, p1->lname, p1->isavailable);
    printf("item2=> %10s, %10s, %4u\n",p2->fname, p2->lname, p2->isavailable);
    printf("item3=> %10s, %10s, %4u\n",p3->fname, p3->lname, p3->isavailable);

    return 0;
}

如果我使用的话,在initializePerson()内部:

person->fname = (char*) malloc (sizeof(strlen(fname)+1));
person->lname = (char*) malloc (sizeof(strlen(lname)+1));

当启用这两个代码行而不是我在上面的源代码中使用的代码行时,当我使用 CodeBlocks IDE 测试代码时可能会出现运行时错误。控制台很可能会卡住并停止工作。如果我使用 ubuntu 终端测试代码,无论输入数据的大小如何,它每天都可以正常工作。

问题:(现在,假设我们使用上一段中的 2 段代码)我知道 sizeof 计算字节,strlen 计算字符数,直到找到 null...但是使用 sizeof 和 strlen 时它们在 malloc() 内一起使用会导致后台冲突吗?似乎有什么问题?为什么代码有如此不稳定、不可靠的行为?为什么?

最佳答案

sizeof(strlen(fname)+1) 没有任何意义。它给出了strlen结果类型的大小,它是一个4字节的整数。所以你最终分配的内存太少。

使用这个:

person->fname = malloc(strlen(fname)+1);

关于c - malloc、sizeof 和 strlen 函数可能发生冲突吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44798757/

相关文章:

c++ - 在成员函数中使用 sizeof()

c - 在 C 中为内部结构返回类型时不兼容的类型

c - 重叠结构和 LARGE_INTEGER

c - 在结构中保存指向数组的指针

c - 在 C 中,无法释放 NULL 并将其分配给 char 指针

c++ - 找出多态对象的大小

c - 如何强制程序使用未对齐的地址?

const double *bar = (const double *) foo;?

c - 错误: difference between perror and fprintf

c++ - sizeof ('ab' ) 是否等于 C++ 中的 sizeof(int)?