[英]C: printf char* return weird last char
I'm trying to understand why I've got a weird character after my printf()
我试图理解为什么在我的
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: printf
返回:
8 i == ' == m == == a == == b == a == i'm a bau
If I remove the '\\0'
I get something like: 如果删除
'\\0'
则会得到类似以下内容:
'ma ba¨Á£´
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
. 因为,您已经分配了
nb_char
个字节,而最后一个索引将是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. 也就是说,在使用返回的指针之前,始终需要通过检查针对
NULL
的返回来检查malloc()
是否成功。
If you remove the \\0
printf has no way to know that the strings ends and will keep incrementing the pointer until it sees a null value and you take the risks of getting a segmentation fault. 如果删除
\\0
printf无法知道字符串结束,并且将不断增加指针,直到看到空值为止,并且冒着出现分段错误的风险。
For strings without a 0 at the end you can use snprintf
对于结尾没有0的字符串,可以使用
snprintf
Also for what you are trying to achieve there's memcpy
or strncpy
另外,对于您要实现的目标,还有
memcpy
或strncpy
check the man pages for more details. 有关更多详细信息,请参见手册页。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.