Search code examples
csegmentation-faultchar-pointer

c function is not working


So the following c function I implemented in segfaulting when I test it with the following code:

char line1[] = "sw $s2, 0($s3)";
char* bc = removeAFromABC(line1);

and this the the method that should return a char pointer = "$s2, 0($s3):

char* removeAFromABC(char* abc) {
    char* a = strtok(abc, " $,\t\n");
    char* b = strtok(NULL, " \t");
    char* c = strtok(NULL, " \t");
    char bc[MAXIMUM_LINE_LENGTH + 1];
    strcpy(bc, b);
    strcat(bc, c);

    return bc;
}

Solution

  • The 'bc' is allocated on stack. When the function returns that address is invalid.

    Try something like this:

    char bc[MAXIMUM_LINE_LENGTH + 1];
    
    void removeAFromABC(char* abc, char * bc, int size) {
        char* a = strtok(abc, " $,\t\n");
        char* b = strtok(NULL, " \t");
        char* c = strtok(NULL, " \t");
    
        /* TODO: use the size parameter here for checking...*/
        strcpy(bc, b);
        strcat(bc, c);
    }