0
votes

So I have this small part of my code (basically the input for my whole program).

It has to take the form of a string with at most 20 characters, and two integers all separated by a space.

eg master 1 1

int main(void)
{

  int i, x, y;
  char input[28];
  char* name = NULL;
  fgets(input, 28, stdin);
  sscanf(input, "%s %i %i", name, &x, &y);
  printf("%s %i %i\n", name, x, y);
  return 0;
}

Basically I'm trying to print it out to see if the program is storing the input correctly, as it has to be stored in a linked list later on.

Everything worked fine, but no matter what I type, It prints out (null) 0 4196064. It seg faults if I put and ampersand infront of name in the sscanf() function as well.

Any ideas on how to fix this would be much appreciated!

2

2 Answers

1
votes

sscanf will not allocate storage for your string.

char name[28];

will work. &name causes seg.fault, because that differs in levels of indirection. What you then pass is a char * * , which is interpreted as char * inside sscanf. As your name variable is on the stack, &name points to the stack, so sscanf will overwrite your stack content. That can easily result in a seg.fault.

0
votes

I am afraid the following changes the type of name, from a character pointer to a character array.Both are different:

  char name[28];

So this would be more appropriate:

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

int main(void)
{

  int i, x, y;
  char input[28];
  char* name = malloc(28*sizeof(char)); //No need to change type of "name"
   printf("Enter your stuff\n");
  fgets(input, 28, stdin);
  sscanf(input, "%s %i %i", name, &x, &y);
  printf("%s %i %i\n", name, x, y);
  return 0;
}

In your code, you have tried to write to the address name using sscanf() even though you haven't allocated any memory to it.This will cause seg-fault and the output will be unpredictable.In the above code malloc() has been used to allocate an appropriate sized memory block and assigns the address to name.Then it works fine.