Jean-philippe Emond Jean-philippe Emond - 1 year ago 95
C Question

C: printf char* return weird last char

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


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);
for(count = starts; count < ends;count++)
word[count-starts] = sentences[count];
printf("%c == \n",sentences[count]);
word[count-starts+1] = '\0';
return word;



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

i'm a bau

If I remove the
I get something like:

'm a ba¨Á£´

Answer Source

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.