Is there a better way to maintain a list of strings in C besides using typedef char* and declaring an array of type string? I am trying to manage a list of member names that join the group via socket program. But every time a new member joins the group – old member names get overridden. Part of the sample code is like this:
typedef char * string;
string List[10];
and new member joins like this:
List[index]=membername;
Thanks.
You’re probably (not enough context) not allocating the strings properly.
only allocates an array of 10
string, i.e. 10char *, i.e. 10 character pointers. It doesn’t allocate any storage for the strings themselves.So if your
membernameabove is e.g. a globalchar *that you’re copying data from the network to, all your slots inListwill end up pointing to that very same memory location.To make it work, you’d need to allocate (and carefully free) all the slots in
List. Something like:For better chances of catching errors early, initially set your
Listto all null pointers.and when a user “goes away”, free and reset that slot to NULL:
That way you’ll get nice, nasty segfaults if you don’t manage your slots carefully enough 🙂