Reputation: 9512
I'm trying to concatenate two chars and get a segmentation error on the line above return. When I used char instead of char*, the (onechar-a + 'A') worked although I wasn't trying to concatenate. If I leave this as char instead of char* I get warnings about casting.
char *carat;
carat = test_carat(ttyinfo.c_cc[VINTR]);
carat = test_carat(ttyinfo.c_cc[VINTR]);
char * test_carat(char onechar)
{
if (onechar >= 32 || onechar !=127)
{
if (iscntrl(onechar))
{
char * returnString = strcat((char*)'^', (char*)(onechar - 1 + 'A'));
return returnString;
}
}
}
Upvotes: 1
Views: 692
Reputation: 20764
That won't work:
strcat((char*)'^', (char*)(onechar - 1 + 'A') )
You shouldn't cast a character to a char pointer. The effect is that the character value (a value <= 255) will be used as address of the character pointer by strcat
, this is why your program segfaults.
You can do that:
char * test_carat(char onechar)
{
if (onechar >= 32 || onechar !=127)
{
if (iscntrl(onechar))
{
char * returnString = (char *)malloc(3);
returnString[0] = '^';
returnString[1] = (onechar - 1 + 'A');
returnString[2] = '\0';
return returnString;
}
}
return NULL;
}
Upvotes: 3