I have a structure as follows:
struct something{
char *string_member;
};
now I created
struct something *s = malloc(sizeof(struct something));
s.string_member = malloc(5); //one way
s.string_member = "some thing wrong"; // second way
While I free the memory pointed by s. How do I free the memory allocated to string_member in the both the cases. Do I have to worry about string_member in second case at all?
You mustn’t free it in your
second wayexample, and you have no way to (portably) make the difference between case one and case two by just looking at the pointer. So don’t do that, make sure you always allocate thestring_memberusingmallocor e.g.strdup. That way, you can alwaysfreeit (once).