When a char *
is passed into this function example: x
:
char* operandType;
char* armRegister;
MY_STRUCT muckVar;
char* armConverter(char* instruction) {
printf("\nA %s\n", instruction);
if (!isdigit(instruction)) {
if (instruction==" "){
operandType="ADD";
return operandType;
}
else if (instruction=="-") {
operandType="SUB";
return operandType;
}
else if (instruction=="=") {
operandType="MOV";
return operandType;
}
else {
muckVar.muckVar1 = instruction;
muckVar.currentCount ;
return instruction;
}
}
else if (isdigit(instruction)) {
muckVar.muckVar1 = instruction;
armRegister = strcat("R",instruction);
muckVar.currentCount ;
return armRegister;
}
}
A segmentation fault is returned. What is it that is causing this error? Could it be due to an invalid pointer being passed into the function?
CodePudding user response:
This will cause a segfault:
strcat("R",instruction)
You can't write to string literals, and strcat
writes to its first parameter.
This will cause a segfault too:
isdigit(instruction)
Here's what the C standard says about the functions from <ctype.h>
, of which isdigit
is one:
In all cases the argument is an int, the value of which shall be representable as an
unsigned char
or shall equal the value of the macroEOF
. If the argument has any other value, the behavior is undefined.
instruction
is a pointer, which in practice will never meet those requirements when implicitly converted to an int
.