0

I have a pointer to a struct.

typedef struct anything{
    char text[MAXI];
    int any;
}Item;

After receiving the input in the struct, the program requests the user in which set he wants to store the struct.

void adding(){
    Item *x = malloc(sizeof(Item));
    printf("Enter an integer.");
    scanf("%d", (&x->any));
    printf("Enter a string.");
    scanf("%s", (&x->text));
    printf("Which set would you like to add the Item to A/B?");
    char inp1 = 0;
    while ((inp1=0),scanf("%s", &inp1) == 1 && (inp1 !=  'A') && (inp1 != 'B')){
        printf("Set does not exist\n");
    }
        if('A' == inp1)
            add(A, x);
        else
            add(B, x);

    flush();
    instructs();
}

When receiving the input (in the while loop), the pointer x is being modified from 0x570ff8 to 0x57f00, which will then point to garbage instead of the input requested below.

Why is the pointer being altered?

Thank you.

The add function:

void add(Array *S,Item *x){
    bool rep = false;
    int i = 0;
    for(i = 0; i<=(S->size); i++){
        if(compStructs(*x,*(S->arr+i)))
            rep = true;
    }
    if(rep == false){
            x = realloc(S->arr, (S->size+1)*sizeof(Item));
            (S->size)++;
            printf("Item has been added");
    }
    else
        printf("The item is already in the set.");

}
user2035045
  • 27
  • 1
  • 5

2 Answers2

0

One error is:

scanf("%s", (&x->text));

which should be

scanf("%s", x->text);

because x->text is already a pointer.

Another error is:

scanf("%s", &inp1)

which should be:

scanf("%c", &inp1)

because you are reading a single char.

HAL9000
  • 3,562
  • 3
  • 25
  • 47
0

This:

  char inp1 = 0;

  while ((inp1=0),scanf("%s", &inp1) == 1 && (inp1 !=  'A') && (inp1 != 'B'))...

You're using a string format specifier (%s) but reading into a char. Even if you just type a single character, scanf will be attempting to store a null-terminated string in the memory pointed to by &inp1.

This memory is on the stack - as is your pointer x. So xis probably being corrupted by the scanf. If you look at the change in value, you'll see the bottom byte of the address is zeroed. This could well be the null terminator being written.

To fix, change your sscanf to use a character format specifier:-

scanf("%c", &inp1) 
Roddy
  • 66,617
  • 42
  • 165
  • 277
  • Thanks for your clear answer. A relatively small problem I'm getting now, is that the printf in the while loop is being accessed 1 time before the user is requested for his input. Also, when the user inputs an invalid input specified by the while loop, the printf is being printed 2 times. – user2035045 Jan 06 '14 at 10:46
  • @user2035045 - That will be because the first two `scanf`s leave a newline lurking in the input buffer. You could be better off using `fgets()`, then `sscanf`. See this question. http://stackoverflow.com/questions/5918079/fgets-doesnt-work-after-scanf – Roddy Jan 06 '14 at 10:57