Escaping non-printable characters in strings
I am trying to escape all of the non-printable characters in a given string.
For example:
input to function -"\x01 foo \xFE"
Should output -"#01 foo #FE"
However the output I receive is "ミ>#01 foo #FFFFFFFE", so basically it outputs garbage at the beginning and end.
I have the feeling that the problem is related to my string handling but I am not sure.
Here is my code:
Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
char *escape_string(char *value)
{
/* Escapes a string */
char *result = (char*)malloc(sizeof(char) * strlen(value));
int i;
for(i = 0; i < strlen(value); i++)
{
char tempval = value[i];
//If character isn't printable
if(isprint(tempval) != 0)
{
strncat(result, &tempval, sizeof(tempval));
printf("Contents: %s\n", &tempval);
}
else
{
char *buf;
size_t sz = 0;
sz = snprintf(NULL, 0, "#%02X", tempval);
buf = malloc(sizeof(tempval) * sz+1);
snprintf(buf, sz+1, "#%02X", tempval);
strncat(result, buf, strlen(buf)-1);
printf("Contents: %s\n", buf);
free(buf);
}
}
char *buffer = (char*)malloc(sizeof(char) * strlen(result));
strncat(buffer, result, strlen(result));
free(result);
printf("Final buffer contents: %s\n", buffer);
return buffer;
}
int main()
{
char *testvalue = "\x01 foo \xFE";
char *testescape = "#01 foo #FE";
assert(escape_string(testvalue) == testescape);
return 0;
}
It would be greatly appreciated if someone could point out what 'is' or 'could' be wrong with my code
Thanks in advance