Guilherme
Guilherme

Reputation: 453

Problems with scanf and struct

I'm trying to read two variables inside a struct but I'm facing some problems using scanf. Here is the code:

typedef struct {
    int pc;
    char* label;
} sb;

... and here is the instantiation of the struct:

sb input;
fscanf (in, "%s%d", input.label, &(input.pc));
printf ("%s %d\n", input.label, input.pc);

I was expecting as output a 'c-string' and an integer but for some reason it gave me: (null) and -971303966.

Upvotes: 0

Views: 649

Answers (3)

DrC
DrC

Reputation: 7698

The main problem is that you have not actually allocated any storage in the structure for the label. One solution is to change the declaration to:

typedef struct {
    int pc;
    char label[80];
} sb;

But please be aware that code is now dangerous because it reads into the buffer without putting any limits on the read so it can overflow the buffer.

Upvotes: 4

PMF
PMF

Reputation: 17328

"Label" in your struct is just a pointer, nothing that can hold a string. You have to either allocate some memory for it

Input.label = (char*)malloc(122);

Or change your struct to

typedef struct { int pc; char label[122]; } sb;

Be carefull about the amount of memory you allocate for the string. Preferably use fscanf_s, so you can declare the maximum length to read.

Upvotes: 1

chux
chux

Reputation: 154592

fscanf(in, "%s%d", input.label, &(input.pc)) results in undefined behavior (UB) because there is no memory associated with input.label in which fscanf() attempts to save.

1) Avoid using fscanf(). Recommend fgets()/sscanf()
2) Check the return value from any scanf() like function.
3) Allocate space for label

void Read_sb(sb *data) {
  sb->pc = 0;
  sb->label = NULL;

  char buf[100];
  if (fgets(buf, sizeof buf, stdin) == NULL) Handle_IOErrroOrEOF();

  char s[sizeof buf];
  if (sscanf(buf, "%s%d", s, &sb->pc) != 2) Handle_FormatError();
  sb->label = strdup(s);
}

Upvotes: 0

Related Questions