0

So, I have a struct member char* and I want to initialize it after allocating node memory .However,this method gets me a Seg Fault. Note. YES, I want a infoPtr. Excuse any syntax errors, these are not the problem I am trying to solve . ALL I want is to correctly pass a char string into name.

struct Info{
    char *name;
}
typedef struct Info *infoPtr;
int main(void){
    enter("google");
}
void enter(char *name){
    infoPtr* info=(infoPtr)malloc(sizeof(infoPtr));
    info->name=strup(name);
}

1 Answers1

4

Here

typedef struct Info *infoPtr;

infoPtr is of struct Info* type, this

infoPtr* info=(infoPtr)malloc(sizeof(infoPtr)); /* info will be of struct Info** type */

should be

infoPtr info = malloc(sizeof(*infoPtr)); /* typecasting is not required */

Side note, its not considered as good practice to typedef a pointer, do read Is it a good idea to typedef pointers?

Also here

info->name=strup(name);

you wanted to use strdup() instead of strup() for e.g

info->name=strdup(name);

Coming to your question ALL I want is to correctly pass a char string into name ? Yes the way you passed argument to enter() is correct except typedefing struct pointer. And passing string literal google like

enter("google");

and defining enter() like

void enter(char *name){ /* Its correct */
  /* play with name */
}
Achal
  • 11,821
  • 2
  • 15
  • 37