Reputation: 93
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.
Upvotes: 0
Views: 113
Reputation: 11
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.
Upvotes: 1
Reputation: 7698
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
}
...
}
Upvotes: 3