Home Why does my C code crash?
Reply: 1

Why does my C code crash?

J R
1#
J R Published in 2018-02-12 19:18:16Z

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.

Benjamin J.
2#
Benjamin J. Reply to 2018-02-12 19:33:30Z

You are accessing memory beyond the limits of the array, which you don't have permission to, which results in undefined behavior. You do that because you have an array of 9 elements, but you attempt to access 10. To rectify, you should write:

// ...
for(int i = 0; i < 9; i++) {
    // ...
}
You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO