Home > OS >  malloc a char pointer member of a struct
malloc a char pointer member of a struct

Time:08-24

How can I allocate memory for a char pointer member of a non pointer struct? Let me explain: Here is a small program:

typedef struct student {
    char *name;
} student;
void main()
{
    /* If I declare a normal struct */
    student Josef;
    /* This line doesn't work */  
    Josef->name = malloc(20*sizeof(char));
    /* But if I declare a pointer to struct student */
    student *PJosef;
    /* This line works */
    PJosef->name = malloc(20*sizeof(char));
}

Could you tell me why? And by the way, I saw in some tutorials, a line that allocates memory for that struct pointer like:
PJosef = malloc(sizeof(student->PJosef)); // (or should I write "struct" before student, even if I typedef-ed?) Is this line necessary? The program works without it.

Thanks ahead.

CodePudding user response:

The second example is invalid. As you do not allocate memory for the struct itself you dereference the dangling pointer and invoke a UB.

It should be

student *pJosef = malloc(sizeof(*pJosef));
if(pJosef)
   pJosef -> name = malloc(20 * sizeof(pJosef -> name[0])); // here also check if allocation failed. 
else { /* error handling */}

Note usage of the objects not types in sizeofs

CodePudding user response:

Using the -> operator in:

student Josef;
Josef->name = malloc(20*sizeof(char));

Will not work because Josef is not a pointer to a struct.

The -> operator can only be used on pointers to type struct. Using the -> operator like you have, is equivalent to doing something like this:

*(Josef).name

This is completely wrong.

Instead you should use the . operator:

student Josef;
Josef.name = malloc(20*sizeof(char));

Note:

student *PJosef;
PJosef->name = malloc(20*sizeof(char));

Will not work because PJosef is a uninitialized pointer and accessing it invokes undefined behaviour.

Instead you must first allocate memory for a struct:

student *PJosef = malloc(sizeof(struct student)); 

if (PJosef == NULL)
{
    fprintf(stderr, "malloc failed");
    // error procedure
}

PJosef->name = malloc(20*sizeof(char));
  • Related