Search code examples
cstrcpy

Confusing strcpy() behaviour, concatenating to other strings


So Im loading comma seperated text from a file.

9780136019701,An Introduction to Organic Chemistry,Timberlake Karen,10,3.54,12-2008
9781506304212,Mathematics for Social Scientists,Kropko Jonathan,7,4.73,12-2015
9781506304213,Discrete Mathematics,Jonathan,15,19.73,10-2013
9780136019702,Chemotherapy,Karen,1,2.54,1-2002

Each line will have six properties and I'm using strtok to split the line. However very confusing behvaiour is happening and that is I read in the ISBN as the first token, copy it into my book.isbn property and then read the next token and copy it into my book.title.

When I print out book.isbn before and after the title token, i notice that the title was added to both book.isbn and book.title . Why is that so? I never mentioned book.isbn anymore. Whats still pointing at it

while (fgets(line, STRING_LENGTH, file) != NULL)
  {
    Book book;

    // Grabbing ISBN
    char *bookToken = strtok(line, ",");
    strcpy(book.isbn, bookToken);

    printf("%s\n", book.isbn);
    // Grabbing Title
    bookToken = strtok(NULL, ",");
    strcpy(book.title, bookToken);

    printf("%s\n", book.isbn);
    
    // Grabbing Author
    bookToken = strtok(NULL, ",");
    strcpy(book.author, bookToken);

The output

9780136019701
9780136019701An Introduction to Organic Chemistry
9781506304212
9781506304212Mathematics for Social Scientists
9781506304213
9781506304213Discrete Mathematics
9780136019702
9780136019702Chemotherapy

Why is it concatenating my title to my book.isbn ?? Also my book.isbn is char isbn[13] so how is it allocating this memory.

I should also say that all my other properties are stored correctly and non of this happens with anything else


Solution

  • Literally after posting i realized my mistake. I was not giving it enough space by only using isbn[13], i now realize it should be isbn[14]