1

The part of the code in question is attempting to decode what register is being used by a MIPS instruction.

This does it by passing in an integer value of the register and then should return a string containing the name of the register. The prince statement that does it is here, where it calls getReg to get the string.

printf("$%d aka $%s\n", itype->rs, getReg(itype->rs));

So far, I've tried this to concatenate them (without the case statements):

char* getReg(int d) {
  char out[4];
  sprintf(out, "a%d", (d - 4));
  return out;
}

But the output results in this:

$6 aka $ìü(

When it should be:

$6 aka $a2

Where am I going wrong with this?

2
  • 3
    Whether out is large enough is irrelevant, returning a local array is still undefined behavior. Commented Feb 12, 2013 at 16:00
  • True, try to give a printf after your sprintf and see. Also, use the GDB, helps a lot Commented Feb 12, 2013 at 16:01

3 Answers 3

4

You are returning address of a local variable (out).

char* getReg(int d) {
 char out[4];
 sprintf(out, "a%d", (d - 4));
 return out;
}

scope and life of out is within function getReg() only.

Allocate memory dynamically for out to return and access outside function. (and large enough), like below

#define SIZE 25
char* getReg(int d) {
     char *out = malloc(SIZE*sizeof(char));
     sprintf(out, "a%d", (d - 4));   // I don't know about calculation??
      return out;
}

and don't forget to free memory.

Sign up to request clarification or add additional context in comments.

2 Comments

1. it should be char *out, 2. sizeof(char) is 1.
@H2CO3 Thanks for char* out. And yes sizeof(char) is 1 but I always do this way :)
0

The array out is local to your getreg function; once the function exits, out no longer exists and the pointer value you return is no longer valid.

It's better to pass the output array as a parameter to the function:

void getReg(int d, char *str)
{
  sprintf(str, "a%d", (d-4));
}

and call it as

char mystr[4];
getReg(r, mystr);

Comments

0

As already mentioned by others the OP returns a reference to storage, which is already invalid if used in the call to printf().

An alternative to provide an external buffer whould be this:

char * getReg(int d, char * out) 
{
  sprintf(out, "a%d", (d - 4));

  return out;
}

...

printf(
  "$%d aka $%s\n", 
  itype->rs,  
  getReg(
    itype->rs, 
    (char[32]){0} /* provide a 32 byte long buffer, initialised to 0s */
  )
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.