0

So I'm working on a program to take in assembly code in a text file and produce the corresponding machine code. However, I'm running into an issue when I'm trying trying to assign values to the members of the AssemblyLine struct. What happens is that when ".fill" is the opcode, arg0 is concatenated to it, and there are also issues with arg0 if I assign value to arg0 first. It is important to note that this only happens when the opcode is ".fill". For example, if the opcode is "add" the values are what I intended for them to be.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct AssemblyLine {
    char opcode[5];
    char arg0[7];
    char arg1[7];
    char arg2[7];
    _Bool initialized;
};

struct Label {
    char name[7];
    int address;
    _Bool initialized;
};

main()
{
   struct AssemblyLine line;
   strcpy(line.opcode, ".fill");
   strcpy(line.arg0, "5");

   printf("%s\n", line.opcode);

   return 0;
}

The output for this program is:

.fill5

My intention is that the output would just be:

.fill

I'm really confused about what would be causing this. Sorry if the answer is really obvious, this is my first time working in C, though I have programmed in C++ before. I was at first thinking that there was no null terminating character, but the string is read fine until after I use the second strcpy. Is fill used as a key word for strcpy or something? I thought maybe it had to do with the '.' but that didn't affect anything when the opcode was ".lw".

Sorry that this post is so long! Thanks for any help!

Rohan
  • 33
  • 2
  • 5

2 Answers2

3

Your array isn't big enough. ".fill" is six characters include the terminating null, but you only allocate memory for five with char opcode[5]. You need to make your array bigger.

Crowman
  • 25,242
  • 5
  • 48
  • 56
1

The string ".fill" is 5 characters + 1 zero character long. That makes 6 characters. But the array 'opcode' is only 5 characters long, so the trailing zero is written to 'arg0'. After that, your copy "5" (2 characters with zero) to 'arg0'. Because 'printf' prints until the trailing zero occurs, it reads out of the bounds of opcode.