-1

I am working out of a textbook learning c. One of the exercises is literally copying the code from the book to demonstrate using scanf. It gets user input for how many times something should be printed. Using a for loop to print out the string, the final characters of the string seem to have gotten jumbled up. Please see below and any help would be appreciated. So far I have tried removing the '\n' to see if maybe it is causing the issue. I have printed out the string before the loop to see if it is an error with the string but it seems to work fine outside the loop. Code below:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char message[10];
    int count, i;

    strcpy(message, "Hello, World!");

    printf("Repeat how many times? ");
    scanf("%d", &count);

    printf("%s\n", message);

    for(i = 0; i < count; ++i)
    {
        printf("%3d - %s\n", i, message);
    }
    return 0;
}

Results:

Repeat how many times? 3
Hello, World!
  0 - Hello, Wor
  1 - Hello, Wor
  2 - Hello, Wor

Thanks in advance.

rayzor
  • 40
  • 1
  • 7
  • 3
    Out-of-bounds write, undefined behavior. – EOF Jun 22 '16 at 22:38
  • 2
    You are writing 14 characters (13 plus zero byte) to an array that only holds 10. You're corrupting the stack and everything after that point is undefined behavior. Pay closer attention! – Tom Karzes Jun 22 '16 at 22:39
  • It's not really valid to explain *undefined behaviour* but it can be satisfying if it fits. *Possibly* when you began to use `i` it corrupted the string, which due to insufficient length, had overflowed into `i`. – Weather Vane Jun 22 '16 at 22:47
  • 1
    I appreciate the reply Weather.. Like I said, it is copied directly from the book and the printed result (in the book) was fine. So an error in the book it is. Granted I would've liked to have picked up on that myself! – rayzor Jun 22 '16 at 22:59

1 Answers1

0

Welcome to StackOverflow. The name of the site is the answer to your question. You are trying to store 14 characters into a string which can hold up to 10. Everything that happens after that is undefined behavior.

What is undefined behavior?

Undefined behaviour is undefined. It may crash your program. It may do nothing at all. It may do exactly what you expected. It may summon nasal demons. It may delete all your files. The compiler is free to emit whatever code it pleases (or none at all) when it encounters undefined behaviour.

Any instance of undefined behaviour causes the entire program to be undefined - not just the operation that is undefined, so the compiler may do whatever it wants to any part of your program. Including time travel.

Read this

Mirakurun
  • 4,859
  • 5
  • 16
  • 32