0

I want to fill typedef struct by function. I tried:

typedef struct{
    char *first_name, *last_name;
    int id;
    Date birthday;
} Person;

void ReadPerson(Person* person){
    person = (Person*)malloc(sizeof(Person));
    person->first_name = readString();
    person->last_name = readString();
    scanf("%d",&(person->id));
    ReadDate(&(person->birthday));
}

the main function:

void main(){
    Person *tmp = NULL;
    ReadPerson(tmp);
}

After calling ReadPerson tmp with Bad Ptr value.

user5742600
  • 33
  • 1
  • 7
  • 2
    Why the (2nd) call to `malloc()` inside `ReadPerson()`? – alk Jan 28 '17 at 15:33
  • It makes no sense, why are you "mallocing" twice? – Claudio Cortese Jan 28 '17 at 15:33
  • The problem might also be in `readString()`. Please provide a Minimal, Complete, and Verifiable example. – Claudio Cortese Jan 28 '17 at 15:36
  • Not understanding your question -- especially the "After calling `ReadPerson` `tmp` with Bad Ptr value." part -- well, this might be a duplicate of [C Programming: malloc() inside another function - Stack Overflow](http://stackoverflow.com/questions/2838038/c-programming-malloc-inside-another-function). – MikeCAT Jan 28 '17 at 15:45
  • 1
    You assigned to the local copy of `person` in the function; that didn't change the pointer in `main()`. You either need to return the allocated structure (and the argument is unnecessary) or you need to pass a pointer to the pointer to the function. – Jonathan Leffler Jan 28 '17 at 16:02
  • Thanks all, the problem in the double malloc, i deleted the on in ReadPerson function and it works great, – user5742600 Jan 28 '17 at 16:05

1 Answers1

0

Maybe it will be more elegant if you malloc a variable in the same code segment when it is defined. If you are defining "Person *tmp" to store the info in main(), then also use malloc in main(). Delete malloc on ReadPerson().

Roberto Paz
  • 356
  • 1
  • 8