So I have this function:
void function (linked_list first, char character){
linked_list new = NULL;
new = (linked_list) malloc(sizeof(linked_list));
new->name[0] = character;
puts (new->character);
...
My problem is that this puts prints out my character followed by some garbage, for example if character = t
, puts will print tőú or something like that.
So my question would be, how do I put a char to an end of a string, without it messing up everything? Oh, and name is defined inside a structure as char name[256];
A string in C needs to be terminated. So you want to do
Otherwise you will see all the "gibberish" that was in memory (malloc doesn't clear the memory, so it's pointing to "whatever was there").
Not also the excellent point made by @self - you are not allocating enough memory for the structure, but only for the pointer to the structure. And in modern C (anything after C89, really) you don't cast the result of malloc - that's "old K&R" (I know, because it's what I learnt...). These days you should just write
By using
sizeof(*new)
you guarantee that the size will be right, even if you change your mind about the type ofnew
in the future... It is the cleanest way to do this (and a nod to @WhozCraig who pointed this out in a comment).