printf - Weird Symbols printed at end of string - C -
so, i've got program parses expressions in line of text such as
11110000 & 11001100 ;
and evaluates binary results. code parsing correctly , evaluating correctly, 2 of test inputs (including 1 above) printf printing these weird symbols after each run.
eos$ ./interpreter < program02.txt 11000000 + eos$ ./interpreter < program02.txt 11000000 2ñ eos$ ./interpreter < program02.txt 11000000 "] eos$ ./interpreter < program02.txt 11000000 ÒØ eos$ ./interpreter < program02.txt 11000000 Ê eos$ ./interpreter < program02.txt 11000000 òj
the string malloc'd this
char *str = ( char * ) malloc ( ( getlength( src ) + 1 ) * sizeof( char ) );
and here how string printed
char *str = binarytostring( val ); printf( "%s\n", str );
any awesome! thanks!
strings null terminated in c. when malloc()
memory, filled whatever in block previously.
one solution fill buffer null character \0
via memset()
(found in string.h
) after using malloc()
so:
int strlen = getlength(src) + 1; char *str = (char*)malloc(strlen * sizeof(char)); memset(str, '\0', strlen); // fill null chars
equally write \0
after final character.
edit: not advice according iharob's comment. taking account, , given know length of string:
int strlen = getlength(src) + 1; char *str = calloc(strlen, sizeof(char)); // allocate strlen * sizeof(char) if (str == null) { // error allocating str - handle error } str[strlen - 1] = '\0'; // zero-based, char after final character
is better solution.
Comments
Post a Comment