How is it possible that the length of this string is increasing?
#include <stdio.h>
#inclu开发者_JS百科de <stdlib.h>
#include <string.h>
char * odd(const char * S, char * dest);
int main()
{
char * source = "abcdefghijklmnopacegiacegi";
unsigned int length = strlen(source);
char dest[length];
printf("%s\n",odd(source, dest));
}
char * odd(const char * source, char * dest)
{
int count = 0;
unsigned int length = strlen(source);
for(int i = 0; i < length; i++)
{
if( (source[i] %2 )!= 0)
{
dest[count] = source[i];
count++;
}
}
return dest;
}
the size of dest increases and produces garbage for any values after the length of source
You have to manually include the ending \0
to the string, that is, at the end of add
, you have to add:
dest[count] = '\0';
You know, the length of strings in C is accounted searching for the \0
character. You have to include one of those at the end of each C string. If not, the string may contain any garbage till the first \0
that will be printed.
Finally, when creating dest
, you have also to increase the length of the reserved space in one to accomodate that ending 0 character. The strlen
does not count that ending 0 character.
Your odd
function forgets to NUL-terminate dest
, so printf
continues to read happily past the intended end of the string, outputting the garbage that happens to be on the stack.
Also, dest
must be one character longer, since strlen
tells the length of the string not including the closing NUL, thus, if source
is by chance all of odd characters, you have a (small) buffer overflow.
You don't copy the terminating \0
.
精彩评论