#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;
}
Inside initializePerson() if i use:
person->fname = (char*) malloc (sizeof(strlen(fname)+1));
person->lname = (char*) malloc (sizeof(strlen(lname)+1));
When these two codelines are enabled instead of the ones i am using in the source code above, i might get a run time error when i test the code using CodeBlocks IDE. Very likely the console freezes up and stops working. If i test the code using ubuntu terminal it works any day without a problem regardless of the size of the input data.
Question: (Now, assume that we are using the 2 pieces of code from the previous paragraph) i know that sizeof counts bytes, and strlen counts the number of characters until it finds null... BUT sizeof and strlen when used together inside malloc() do they cause a conflict in the background? What seems to be the problem? why the code has such an erratic,unreliable behavior? why?