Jacob Jacob - 1 month ago 8
C Question

Can i not set null termination on a char array?

I try to make a small function to get a string between two tags. But I get segfault on

str[len -3] = '\0';


Is it not possible to add a nulltermination to the string passed and then send a pointer back?

Is it bad practice to change the index of the pointer insted of copying it over to a buffer and send it back?

I get a memory leak from the 3 bytes never getting freed?

/*
format for a message
<m>Hello world!</>13594750394883323106
<m>"msg"</><checksum>
*/
//returns the string beetween tags
char* GetMessage(char* str)
{
int len = strlen(str);
for(int i = 0 ; i < len;i++)
{
if(str[i] == '<' && str[i+1] == 'm' && str[i+2] == '>')
{
if(str[len-3] == '<' && str[len-2] == '/' && str[len-1] == '>')
{
str[len - 3] = '\0';
return &str[3];
}
}

}
return NULL;
}

Answer

To resume answers for the questions.

1) Is it not possible to add a nulltermination to the string passed and then send a pointer back?

It turned out that the string passed as a literal was the problem in this case. Jonathan Leffler pointed this out in the comments and that was exactly how I tested the function.

GetMessage("<m>Hello world!</>");

When tested in conjunction with other functions answering without literals it worked well.

GetMessage(ReadSerialData());

2) Is it bad practice to change the index of the pointer instead of copying it over to a buffer and send it back?

This appears to be of preference. But should not caus any problems.

3) I get a memory leak from the 3 bytes never getting freed?

This was really good explained here


Thanks for all the inputs!

Comments