Gio
Gio

Reputation: 21

Problems with scanf and strings in a while loop

I don't understand what's wrong with this part of code of my program. I'm using a while cicle for asking the user to insert a string that will be saved to a temporary (char *name) string and then passed as argument of a function. However the problem is when I use scanf function. This is the code:

char *name;
size_t i=0;

while(i<size){
    printf("Insert #%zu item name: ",i+1);
    scanf("%s",name);
    printf("Insert #%zu item price: ",i+1);
    scanf("%u",&price);
    item=item_cons(item,name,price);
    i++;
}

Upvotes: 0

Views: 543

Answers (2)

Ameer Aamar
Ameer Aamar

Reputation: 1

try to use char name[100]={'\0'} this assumes that the larger name you will get is a 10

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

In your code

scanf("%s",name);

you did not allocate memory for name, the pointer. It points to invalid memory location and attempt to use it to store any value will invoke undefined behavior.

You need to allocate memory to name before you can use that to store anything in the memory pointed by it. You can either

  • make name an array, like char name[32] = {0}; and then use it like scanf("%31s",name); (usually preferred)

or,

  • allocate dynamic memory to char *name, using malloc() or family.

Upvotes: 2

Related Questions