-3

So, I've got a program that parses expressions in a line of text such as

11110000 & 11001100 ;

and evaluates the binary results. My code is parsing correctly and evaluating correctly, but for two of my test inputs (including the one above) my printf is also 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 is malloc'd like this

char *str = ( char * ) malloc ( ( getLength( src ) + 1 ) * sizeof( char ) );

And here is how the string is printed

char *str = binaryToString( val );
printf( "%s\n", str );

Any help would be awesome! Thanks!

1 Answers1

1

Strings are null terminated in C. When you malloc() memory, it will be filled with whatever was in the block previously.

One solution is to fill the buffer with the null character \0 via memset() (found in string.h) after using malloc() like so:

int strLen = getLength(src) + 1;
char *str = (char*)malloc(strLen * sizeof(char));
memset(str, '\0', strLen); // Fill with null chars

Equally you could just write a \0 after the final character.

EDIT: This is not good advice according to iharob's comment. Taking this into account, and given you know the length of the 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, so char is after final character

Is a better solution.

Arite
  • 459
  • 3
  • 13
  • 1
    This is very bad advice in so many ways, 1. [Do not cast the result of `malloc()`](http://stackoverflow.com/a/605858/1983495), 2. `sizeof(char) == 1` **by definition**. 3. Your `memset()` is completely unnecessary, if you are allocating `strLen` characters, just `str[strLen - 1] = '\0'` is enough, using `memset()` for that might, hide bugs, when you try for example to debug the program with tools like [valgrind](http://www.valgrind.org). 4. There exists `calloc()`. 5. Don't dereference the pointer if you didn't check for `NULL` yet. – Iharob Al Asimi Apr 22 '15 at 17:04