James
James

Reputation: 771

Segmentation fault on sscanf in C

Very new to C so please bear with me! I'm trying to read 3 arguments separated by spaces from "instruction" into the 3 strings using sscanf. I've got the following code so far:

char * buffer;
buffer = (char*) malloc (5000);
sscanf(instruction, "%s %s %s", &opcode, &arg1, &arg2, buffer);

However whilst it compiles fine, there is a seg fault on the last line where the sscanf is. Last time I saw this error it was because there wasn't enough memory in the variables to store the information. I'm guessing I'm not using malloc properly?

I can't post the entire code unfortunately as it doesn't belong to me.

Upvotes: 0

Views: 1828

Answers (2)

Matt
Matt

Reputation: 22133

You are using sscanf improperly. Try this:

#define BUFFER_SIZE 1024 /* generally good practice to use constants */

char *opcode = (char *)malloc(BUFFER_SIZE);
char *arg1 = (char *)malloc(BUFFER_SIZE);
char *arg2 = (char *)malloc(BUFFER_SIZE);
sscanf(instruction, "%s %s %s", opcode, arg1, arg2);

Depending on how you use these variables, it might be better to allocate them on the stack:

char opcode[BUFFER_SIZE];
char arg1[BUFFER_SIZE];
char arg2[BUFFER_SIZE];
sscanf(instruction, "%s %s %s", opcode, arg1, arg2);

Upvotes: 1

mity
mity

Reputation: 2349

Remove the ampersands. The three %s escapes will then fill them (assuming you have them pointing to valid memory and the buffers are large enough). Note the buffer will be never filled as your format strings refers only to three args

Upvotes: 4

Related Questions