Kyle Jensen
Kyle Jensen

Reputation: 429

Segmentation Fault when using strrchr()

I am trying to remove the last comma from a record. I use strrchr() to find the last occurrence of ',' in the record and set it to the null termination. For some reason it is not finding the last occurrence of the comma and giving a "segmentation fault 11" error.

void buildAssemblyRecord(char asmRecord[], const char* data)
{
char* record = asmRecord;
record += sprintf(record, "dc.b\t");

int i = 0;
for(i = 0; i < strlen(data); i++)
{
    record += sprintf(record, "$%.2X, ", data[i]);
}

//Remove trailing comma
char* whereComma = strrchr(record, ',');
if(whereComma != NULL)
{
    *whereComma = '\0';
}
}

Theoretically this should work perfectly, as I use this method all the time with regular old strchr to remove new line characters from fgets input.

Could anyone let me know whats going on?

Upvotes: 0

Views: 539

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409216

If you read e.g. this sprintf (and family) reference you will see that it returns the length of the string it writes.

When you do record += sprintf(...) you make record point beyond the the newly printed string. Which is good for your loop. But then you use record directly in the strrchr call, and strrchr can't find the character you look for and will return NULL which you do not check for. So when you dereference whereComma you will dereference a null pointer and have undefined behavior and your crash.

You need to reset the pointer after the loop:

record = asmRecord;

Upvotes: 3

Related Questions