Question

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];

Was it helpful?

Solution

A string in C needs to be terminated. So you want to do

new->name[0] = character;
new->name[1] = '\0';

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

new = malloc(sizeof(*new));

By using sizeof(*new) you guarantee that the size will be right, even if you change your mind about the type of new in the future... It is the cleanest way to do this (and a nod to @WhozCraig who pointed this out in a comment).

OTHER TIPS

puts expects strings to be null terminated.

If you're just copying one character in to the string, add a null terminator:

new->name[0] = character;
new->name[1] = '\0';
puts (new->name);

Assuming linked_list is a typedefed pointer( it must be since you cast your malloc with it ) then your malloc is allocating only enough space for a pointer. You should be allocating space for the entire struct.

new = (linked_list) malloc(sizeof(*linked_list));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top