简体   繁体   中英

Getting segmentation fault while printing output

I am trying to know how the array in c is working. so i was implementing some basic array concepts. when i run the program i got the exact output but at the end of the output it says segmentation fault .

int main(void)
{
    int a[] = {};
    printf("Enter the number:");
    int n = get_int();
    int m = 0;

    for(int i = 0; i<n; i++)
    {
        printf("insert:");
        m = get_int();
        a[i] = m;
    }

    for(int j = 0; j < n; j++)
    {
        printf("%d\n", a[j]);
    }

}

output:

Enter the number:3
insert:1
insert:2
insert:3
1
2
3
~/workspace/ $ ./arr_test
Enter the number:5
insert:1
insert:2
insert:3
insert:4
insert:5
1
2
3
4
5
Segmentation fault

see for the first output it has a size of 3 it doesn't show segmentation fault but for second one it has a size of 5 it shows. so why its happening and what mistake i made.

You need to allocate memory for the array. Something like:

int main(void)    {
   int *a;
   ...
   int n = get_int();
   ...
   a = malloc(n * sizeof(int));
   if (!a) {
      // Add error handling here
   }
   ...
}

If you know the size of the array you want to make ahead of time, declare it like int a[128]; instead of just int a[]; so a at indices 0 to 127 will be safe to write to (and subsequently read from).

If you want to declare an array of size n at runtime, use int a[] = malloc(n * sizeof(int)); or int *a = malloc(n * sizeof(int)); . Make sure a is not NULL before using it, and remember to call free(a); when you are done with it to avoid a memory leak.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM