Joachim Schmitz
6/12/2011 9:45:00 AM
Uno wrote:
> On 06/12/2011 01:05 AM, Barry Schwarz wrote:
>> On Jun 11, 11:06 pm, Uno<U...@example.invalid> wrote:
>>> $ indent -kr hist1.c
>>> $ cc -Wall -Wextra hist1.c -o hist
>>> $ ./hist
>>> Segmentation fault
>>> $ cat hist1.c
>>> #include<stdio.h>
>>> #define SIZE 100000
>>>
>>> int main(void)
>>> {
>>> int c;
>>> long counter = 0;
>>> long a[SIZE];
>>
>> If long is 4 bytes, this reserves 400,000 bytes. If 8, then 800,000.
>
> I'm sure I have a gig of memory.
But you're not using it for long a[SIZE], so accessing a[SIZE+1] would
result in a SIGSEGV usually.
>>
>>> long i, j;
>>> FILE *fp;
>>>
>>> fp = fopen("shoulder.wmv", "rb+");
>>>
>>> for (i = 0; i< SIZE; ++i) {
>>> a[i] = 0;
>>> }
>>>
>>> for (j = 0; j< 7000000; ++j) {
>>> c = fgetc(fp);
>>>
>>> if (c != EOF) {
>>>
>>> a[counter] = c;
>>
>> Depending on the size of your file, this could easily exceed the
>> amount of space reserved for a. When that happens, your program
>> exhibits undefined behavior.
>
> I've tried different values here, but 20 million is greater than 19
> and change.
>
> -rw-r--r-- 1 dan dan 19573712 2011-06-05 17:32 shoulder.wmv
> $ cc -Wall -Wextra hist2.c -o hist
> $ ./hist
> Segmentation fault
> $ cat hist2.c
> #include <stdio.h>
> #define SIZE 20000000
>
> int main(void)
> {
> int c;
> long counter = 0;
> long a[SIZE];
> long i, j;
> FILE *fp;
>
> fp = fopen("shoulder.wmv", "rb+");
>
> for (i = 0; i < SIZE; ++i) {
> a[i] = 0;
> }
>
> for (j = 0; j < SIZE; ++j) {
> c = fgetc(fp);
>
> //printf("c is %d\n", c);
>
>
> if (c != EOF) {
>
> a[counter] = c;
> counter++;
> } else {
> for (i = 0; i < 100; ++i) {
> printf("i and frequency is %ld %ld\n", i, a[i]);
> }
>
>
> break;
> }
> }
> printf("Counter reached %ld\n", counter);
> fclose(fp);
> return 0;
> }
>
> // cc -Wall -Wextra hist2.c -o hist
> $
>
>
>>
>> Why are you using a long to store a character?
>
> A long is intended to store the frequency of a given char.
>>
>>> counter++;
>>> } else {
>>> for (i = 0; i< 100; ++i) {
>>> printf("i and frequency is %ld %ld\n", i, a[i]);
>>
>> This code does not compute any frequencies. Any non-zero a[i] has
>> had its value changed exactly once and the value is set to the i-th
>> character in the file.
>
> This code hasn't done anything yet; that is true.
Have you tried using a debugger on this? Where does the debugger report the
program to fail?
You probably want to add -g to the compiler options.
Bye, Jojo