Jean-philippe Emond Jean-philippe Emond - 2 months ago 23
C Question

C: printf char* return weird last char

I'm trying to understand why I've got a weird character after my

printf()


char* extract_word()
{
char* sentences = "hi! i'm a banana!";
int starts = 4;
int ends = 12;
int count;
int nb_char = ends-starts+1;
char* word = malloc(nb_char);
printf("\n\n%d\n",ends-starts);
for(count = starts; count < ends;count++)
{
word[count-starts] = sentences[count];
printf("%c == \n",sentences[count]);
}
word[count-starts+1] = '\0';
printf("\n\n%s",word);
return word;
}


The
printf
returns:


8

i ==
' ==
m ==
==
a ==
==
b ==
a ==

i'm a bau



If I remove the
'\0'
I get something like:


'm a ba¨Á£´


Answer

In your code

   word[count-starts+1] = '\0';

is off-by-one and basically that out-of-bound access invokes undefined behavior.

You should change your code to

   word[nb_char-1] = '\0';

because, you have allocated nb_char bytes and the last index would be nb_char-1.

That said, it's always required to check for the success of malloc() by checking the return against NULL before using the returned pointer.

Comments