2

Constants:

#define MAX_OPCODE_NAME_LEN 4

I have an array of structs:

OPCODE *mot[NUM_OPCODES];

Struct def:

typedef struct opcode {
char name[MAX_OPCODE_NAME_LEN + 1];
char format;
int type;
} OPCODE;

In my code:

strcpy(mot[0]->name, "hlt");
strcpy(mot[1]->name, "add");
strcpy(mot[2]->name, "sub"); // seg fault on this command
strcpy(mot[3]->name, "mul");
// ...more code follows

My code gives me a segmentation fault here and I'm not sure why, since it should have enough space to hold 5 characters (4 char followed by '\0'), so it shouldn't be running out of space, and I'm just copying a string literal into a static memory location. Perhaps I defined the struct incorrectly or used the pointer arrow in the wrong spot?

3
  • 4
    Did you allocate your array of pointers called mot? Commented Apr 8, 2013 at 20:56
  • I have it defined as OPCODE *mot[NUM_OPCODES]; but that's all I did. Do i need to malloc something else for it? Commented Apr 8, 2013 at 20:57
  • 1
    That does not allocate any memory that the 4 pointers point to that you created. Commented Apr 8, 2013 at 20:58

1 Answer 1

4
OPCODE *mot[NUM_OPCODES];

is an array of pointers to OPCODE. Not an array of OPCODEs.

You have either to allocate OPCODE memory for each pointer stored in mot or (easier way for the current code) just make mot an array of OPCODEs

OPCODE mot[NUM_OPCODES];
       ^^

and access the values as

strcpy(mot[0].name, "hlt");
strcpy(mot[1].name, "add");  ....
             ^^
Sign up to request clarification or add additional context in comments.

1 Comment

OPCODE mot[NUM_OPCODES]; and strcpy(mot[0].name, "hlt"); worked, thanks.

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.