-
Segmentation fault
Hello to all,
I am having a problem with my program. I am receiving an error message "Segmentation fault" when I run it. Here is my code:
Code:
main( int argc, char **argv )
{
FILE *input ;
FILE *output ;
char buffer[1000] ;
char sequence[100000000] ;
char c ;
int i = 0 ;
if( ! ( input = fopen( argv[1], "r" ) ) )
{
printf( "COULD NOT OPEN FILE %s - Exit!\n", argv[1]) ;
exit(1) ;
}
while(fgets(buffer, 1000, input))
{
// start obtaining bases after ORIGIN
if(strstr(buffer, "ORIGIN"))
{
int n = 0 ;
while((c=getchar()) != '/')
{
if(c >= 'a' && c <= 'z')
{
sequence[i++] = c ;
}
}
}
}
printf("Here is the sequence:\n" ) ;
return(0) ;
}
The sequence I am trying to build up is going to be about 5 million characters and the file I am inputing is pretty big; about 12 MB. Any help would be great.
Thanks
-
Youre probably blowing the stack. Try using malloc to assign large areas of memory for use, see if that helps.
-
Code:
char sequence[100000000] ;
That's really, really big for an array -- especially an array stored on the stack. As mike_g has indicated, if you use malloc or even declare that array globally it might solve your problem. (That is, put that line outside of main(), right before it.)
Personally, I suggest you use malloc(). A simple solution would go like this:
Code:
long filesize;
char *data;
/* open the file input in here somewhere */
fseek(input, 0, SEEK_END); /* set the file pointer to the end of the file */
filesize = ftell(input); /* store the current file position -- i.e., the size of the file in bytes */
/* allocate one byte of memory for every byte in the file */
data = malloc(filesize * sizeof(*data));
/* do stuff with the data array, reading the file etc */
free(data); /* don't forget to clean up after yourself . . . . */
That's not an optimal solution, of course; you don't need enough memory to store every byte in the file, just every alphabetic character. But a better solution would involve realloc() and I don't feel like explaining that here . . . .
-
Unfortunately, 100000000 is about 95 MB--too big for the stack! The stack can hold about 1 MB by default, but varies from OS to OS and settings in some linkers/compilers.
And I really doubt you need all that memory either. You need a dynamic memory approach. Allocate a reasonable size with malloc, keep track of size, if your array exceeds the size, reallocate using realloc and free later.
And main returns int, so it should be "int main" and not "main".