0

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++;
}
2
  • However the problem is when I use scanf function what is it? Commented Jun 21, 2016 at 21:28
  • Oh sorry I forget to insert that. Ok this is the problem: When I insert the string it prints for (size) times insert 1-2-3-4-...-size item name and insert 1..size item price Commented Jun 21, 2016 at 21:29

2 Answers 2

2

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.
Sign up to request clarification or add additional context in comments.

5 Comments

I used name=malloc(sizeof(char*)*size); and it works Thanks you!
@Gio No, it does not look like, rather, you may want name= malloc( sizeof(*name) * size); Note: 1) You need to check for success of malloc() 2) You got to free the memory afterwards. What's the problem with the array?
Wait, just because it works, doe not mean it's correct. name=malloc(sizeof(char*)*size); is wrong, as you want to allocate memory for chars, not char *s... see my previous comment ^.
Better to say name lacks initialization - its contents are not specified. C does not specify the name points to an invalid memory location.
BTW: "attempt to use (by de-referencing) to store any value will invoke undefined behavior." is true and somewhat surprisingly even reading the pointer value is UB.
0

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

1 Comment

Add some explanation with answer for how this answer help OP in fixing current issue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.