Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Segmentation fault when passing a pointer into function

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 macro EOF. 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading