Extremely strange bug in gcc/g++
I have Linux installed on both my laptop (Debian Woody r3.2) and my desktop (RedHat 8). On both of these machines there is a very strange bug in gcc/g++. I am posting the code that runs and the code that causes a segmentation fault. If anyone knows why this bug occurs, please let me know.
The code that causes a segmentation fault is given below # include <stdio.h> void main (void) { int k,max_val; int *array; max_val = 10; for (k=0;k<max_val;k++) { array[k] = k*max_val; } fflush(stdin); fflush(stdout); for (k=0;k<max_val;k++) printf ("%d ", array[k]); } This compiles correctly in both gcc/g++ but causes a segmentation fault while running. The code that runs correctly is given below # include <stdio.h> void main (void) { int k,max_val, pos, val; int *array; max_val = 10; for (k=0;k<max_val;k++) { array[k] = k*max_val; } fflush(stdin); fflush(stdout); for (k=0;k<max_val;k++) printf ("%d ", array[k]); } This runs perfectly and causes the array of 10 elements 0 10 20 30 40 50 60 70 80 90 to be displayed. It will be observed that there is absolutely no change between the two segments in the program except for the introduction of two unused variables in segment 2. It is beyond me why code segment 2 works and 1 does not. If any one has an answer, please let me know. Regards, Maidros |
# include <stdio.h>
#define ARRAY_MAX 10 /* main should return "int" value */ int main (void) { int k,max_val; /* you need to allocated storage, not an non initialized pointer */ int array[ARRAY_MAX]; max_val = ARRAY_MAX; for (k=0;k<max_val;k++) { array[k] = k*max_val; } /* // flushing stdin is useless - fflush flushed output buffers fflush(stdin); */ fflush(stdout); for (k=0;k<max_val;k++) printf ("%d ", array[k]); /* you should return "int" from main */ return 0; } |
You have a pointer to an integer which you then treat as an array without having requested the appropriate memory using alloc. That explains the segmentation fault. As for why the second one works, well I think you're just lucky.
Code:
int main (void){ |
Quote:
Regards, Maidros |
All times are GMT -5. The time now is 06:40 PM. |