Myn*_*cks -1 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;
}
Run Code Online (Sandbox Code Playgroud)
如果我使用的话,在initializePerson()里面:
person->fname = (char*) malloc (sizeof(strlen(fname)+1));
person->lname = (char*) malloc (sizeof(strlen(lname)+1));
Run Code Online (Sandbox Code Playgroud)
当启用这两个代码行而不是我在上面的源代码中使用的代码行时,我可能会在使用CodeBlocks IDE测试代码时遇到运行时错误.控制台很可能冻结并停止工作.如果我使用ubuntu终端测试代码,无论输入数据的大小如何,它都可以在任何一天工作而不会出现问题.
问题:(现在,假设我们正在使用前一段中的2段代码)我知道sizeof计算字节数,strlen计算字符数直到找到null ...但是当malloc内部一起使用时,sizeof和strlen ()它们是否会在后台引发冲突?什么似乎是问题?为什么代码有这种不稳定,不可靠的行为?为什么?
sizeof(strlen(fname)+1)没有任何意义.它给出了结果类型的大小strlen,它是4个字节的整数.所以你最终分配的内存太少了.
用这个:
person->fname = malloc(strlen(fname)+1);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
150 次 |
| 最近记录: |