Home Why does my C code crash?
Reply: 0

Why does my C code crash?

user10461
1#
user10461 Published in September 20, 2018, 10:34 pm

I'm trying out the syntax in C, as it's new to me. I was just starting with arrays, loops and random numbers, so I wrote this really simple test code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    srand(time(NULL));
    int arr[9];

    for(int i=0; i<10; i++) {
        arr[i] = rand();
        printf("%d \n", arr[i]);
    }
}

I compile it with gcc and run from command prompt. Runs fine, prints each element in the array... And then crashes. Why? Is there something with the code logic?

Thank you in advance! This is my first question here, so I apologize in advance if I made any mistakes in question asking rules.

share|improve this question

closed as off-topic by lurker, melpomene, ikegami, user3386109, Sneftel Feb 12 at 19:35

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question was caused by a problem that can no longer be reproduced or a simple typographical error. While similar questions may be on-topic here, this one was resolved in a manner unlikely to help future readers. This can often be avoided by identifying and closely inspecting the shortest program necessary to reproduce the problem before posting." – lurker, melpomene, ikegami, user3386109, Sneftel
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 2
    i < 10 ---> i < 9 – machine_1 Feb 12 at 19:19
  • 5
    The array is of 9 elements. You are accessing 10. – Eugene Sh. Feb 12 at 19:19
  • Accessing array out of bound make program behave erroneous (invokes undefined behavior). Program crash is one of them. – haccks Feb 12 at 19:20
  • 2
    @JR General rule in C: If you're very, very lucky, the compiler will catch your mistakes. If you're merely lucky, your mistakes will crash the program. But if you're not lucky, your mistakes will silently corrupt data elsewhere or lead to unpredictable behavior later on in the program. – melpomene Feb 12 at 19:25
  • 1
    Also, I'm afraid that you won't win the 'Original Title of the Month' award:( – Martin James Feb 12 at 20:15

1 Answer 1

active oldest votes
up vote 1 down vote
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.304499 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO