0

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;
}
letter Q
  • 14,735
  • 33
  • 79
  • 118

3 Answers3

0

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);
}
user1764961
  • 673
  • 7
  • 21
0

bc is automatic local variable to your function removeAFromABC. Never return a pointer to an automatic local variable. Because, the variable bc doesn't exist once removeAFromABC returns, so the pointer to it will be invalid.

haccks
  • 104,019
  • 25
  • 176
  • 264
0

You have a return type of char * so with bc declared as:

char bc[MAXIMUM_LINE_LENGTH + 1];
it is not a legal return type. (it would not build like that)

Try this instead:

#include <ansi_c.h>
#include <windows.h>

#define MAXIMUM_LINE_LENGTH 260
char* removeAFromABC(char* abc);

int main(void)
{
    char line1[] = "sw $s2, 0($s3)";
    char* bc = removeAFromABC(line1);
    printf("bc is %s", bc);
    return 0;
}

char* removeAFromABC(char* abc) 
{
    char* a = strtok(abc, " $,\t\n");
    char* b = strtok(NULL, " \t");
    char* c = strtok(NULL, " \t");
    char *bc = malloc(MAXIMUM_LINE_LENGTH); //to match return type
    strcpy(bc, b);
    strcat(bc, c);

    return bc;
}

Note: I did not completely restructure your code, but it does need some more work. i.e. allocate and free memory as needed.

ryyker
  • 22,849
  • 3
  • 43
  • 87