1

I'm filling an array with 40 pseudo-random capital letters and then converting the array into a string by terminating it with a null character at the 41st element, but my program crashes when I do the latter. Here is the code:

char s1[41]; int i; for (i = 0; i < 41; i++) { s1[i] = ((rand() % 26) + 'A'); } s1[i] = '\0'; puts(s1); 

The program runs just fine if I print out each character in the array one at a time without the null assignment statement, but everything fails when the null assignment is included. I am required to convert the array into a string and then use the puts function. Why is this happening? Is a string not simply an array of characters terminated with a '\0' (null)? What is causing this? Is this a compiler error? Attached is a screenshot of the error message.

I am using Microsoft Visual Studio Express 2013, if it matters.

8
  • 8
    Off by one. You are writing right behind the array, to s1[41]. Commented Apr 28, 2015 at 19:41
  • 3
    i < 41 --> i < 40 Commented Apr 28, 2015 at 19:42
  • Unrelated, but you might want to look into random number generation. (rand() % 26) = veeery bad. Commented Apr 28, 2015 at 19:43
  • You're lucky this program crashes. If it hadn't, this bug might have gone unnoticed for a long time! Commented Apr 28, 2015 at 19:44
  • 1
    @gldraphael He does that to nul terminate the string, it isn't there by default unless s1 had static storage duration. Commented Apr 28, 2015 at 20:09

3 Answers 3

1

To clarify the comments, if it's not obvious to you: i==41 after exiting the loop, so s1[i] is writing outside the bounds of the array. This is undefined behavior and, as mentioned, you're lucky it crashed.

Sign up to request clarification or add additional context in comments.

Comments

1

Just realized that I was assigning the null character to a location outside of the array. I needed to decrement i.

2 Comments

No: make it char s1[41 + 1];
Don't decrement i, change your loop limit. for (i = 0; i < 40; i++) will write your 40 values (i.e. indexes 0-39, then the 41st value goes in s[i] = 0; where i is 40.
0

Make 41 to 40 then try again

i < 40 

Usually trial and error with this number can give you different results

 char s1[41]; int i; for (i = 0; i < 40; i++) { s1[i] = ((rand() % 26) + 'A'); } s1[i] = '\0'; puts(s1); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.