0

I'm writing simple program in C and got stucked. I have three functions:

void changeStatusOfBook(User users[], Book books[]) {
  char *id= askForBookID();
  Book book = getBookById(books, id);
  .
  .
  .
}

char * askForBookID() {
  char id[6];
  printf("Tell me which book (ID)\n");
  scanf_s("%5s",id, 6);
  return id;
}

Book getBookById(Book books[], char bookID[]) {
  int counter = 0;
  //bookID becomes a trash here
  .
  .
  .
}

The problem is: In the first function I get correct user string input, but when I pass it to third function I'm getting some trash in it. How to fix it?

1
  • Compile with all warnings & debug info. Notice that arrays are decayed into pointers when passed as arguments. Commented Feb 18, 2017 at 12:47

2 Answers 2

3

You can't return a local variable char id[] from a function.It's memory is on the stack and when the function returns all stack memory for that function and its local variables are no more accessible.

when memory is need on the stack for another program it overrides the memory space for char id, and this becomes a problem for your program.

 char * askForBookID() {
      //char id[6];
        char *id = malloc(sizeof(char)*6);
        if(!id){ //check if malloc got some memory for id
           printf("Sorry not enough memory"); return NULL;

         }

       printf("Tell me which book (ID)\n");
       scanf_s("%5s",id, 6);

       return id;
}
Sign up to request clarification or add additional context in comments.

4 Comments

I prefer my answer as it doesn't make any assumptions about the implementation of c on the platform, but this answer is probably more useful. Have an upvote.
@Bathsheba i agree with you.
Thanks it worked - I was trying to use malloc in changeStatusOfBook() but dunno why I didn't think about askForBookID().
@MrKaszu oh i see, i hope i could help. When you need memory in a function you need to use malloc. Sometimes making the variable static also but i prefer malloc. don't forget askForBookID() is now responsible for freeing memory use free(askForBookID()) when done with it.
3

The function askForBookID returns the address of the first element of an array with automatic storage duration.

The behaviour on your using that pointer oncce the function has been called is undefined.

Use malloc instead.

Comments

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.