I sense something smelly... Namely, that all your variables seem to be local variables (on the stack) that cease to exist when your function returns.
So would your function end with
return abc;
then you loose everything because you said abc= &def; and def is also a local variable. So yes, you can simply do abc->line= p1; but after the return you have lost abc (which points to def which was a stack variable that then no longer exists) and hence you have also lost abc->line and so you have a memory leak.
So you should expand the code you show us for us to be able to say "Yes you can do that".
The following is an example of a function that is wrong:
struct el{
char *line;
struct el *next;
};
struct el *example(void)
{
struct el *abc, def; // def is a local variable
char *p1;
char buffer[100];
abc = &def;
gets(buffer);
p1 = malloc( strlen(buffer) + 1 );
strcpy( p1, buffer);
abc->line= p1;
return abc; // def won't exist anymore after the function returns
}
To fix this error, you should also do abc= malloc(sizeof(struct el)); or pass a pointer variable to the function, for example:
void example2(struct el *abc)
{
char *p1;
// ...
abc->line= p1;
}
and call as for example:
int main(void)
{
struct el pqr = {0};
example2(&pqr);
// ...
}
gets2)sizeof(strlen(buffer))is completely wrongabc->line = p1doesn't create a copy. Freeing p1 frees the other pointer too (same addresses)fgetsbufferhas size 100, by sending in input more than 100 chars will make gets write out of bounds, and that will probably crash your program).abc->line = p1;does exactly what you think it does. It takes the value in p1 (which is an address) and saves that same value into abc->line. Now abc->line and p1 store the same address.