Message-Id: <199803211409.QAA20152@ankara.duzen.com.tr> From: "S. M. Halloran" Organization: User RFC 822- and 1123-compliant To: zappaz AT xtra DOT co DOT nz, djgpp AT delorie DOT com Date: Sat, 21 Mar 1998 16:13:37 +0200 MIME-Version: 1.0 Content-type: text/plain; charset=US-ASCII Content-transfer-encoding: 7BIT Subject: Re: Why why why??? (help me with this code....) In-reply-to: <6f0c4b$a9p$1@wolfman.xtra.co.nz> Precedence: bulk On 22 Mar 98 zappaz AT xtra DOT co DOT nz was found to have commented thusly: > I'm using DJGPP on Win95 platform and this little procedure is giving > me a real headache. All it does is return a frequency table (array of > longs) of how often each byte appears in the file "namein". If I > include the line marked with ' > ' then the following while loop never > gets executed. ? Also, if I include the line marked with ' >>> ' the > program crashes, even if the ' > ' line _is_ included. ? ? Compiles > OK. > > > > long *frequencyTable(char *namein) { > FILE *infile; > int c; > long *freq; ^^^^^^^^^^^ This is your problem right here > memset(freq,0,2); > > infile = fopen(namein,"r"); > printf("Opening %s successful.\n", namein); > > for (int i=0;i<256;i++) freq[i]=0; > while((c=getc(infile))!=EOF) > { > printf("got \"%c\"\n",c); // not really neccesary > >>> freq[c]++; > } > fclose(infile); > return freq; > } > > > Also, I've often noticed that adding a printf statement in a loop > makes a big difference to how that loop runs (usually the difference > between running or not running at all). Is this just something strange > with DJGPP or is there something I don't know? > Back to the School of C Programming for you, I think. You have failed to initialize the pointer variable 'freq' properly. Either use malloc() to assign the pointer to a block of (dynamic) memory: long *freq; /* as you have it */ /* somewhere before you reference 'freq' at all */ if ((freq = malloc(256 * sizeof(long))) == NULL) /* report an error, maybe return from function, then buy more memory */; /* more code */ free(freq); /* don't forget to free before returning from func */ Probably it is perhaps better, in your case, to declare 'freq' as an array of 256 long integers: long freq[256]; /* a definition of an 'automatic' variable */ Also in your for loop marked with '>', you set all the values in the array with '0'. I think it is better form to put as a suffix on long constants the character 'L', although I don't believe it is required to generate a compiler error if you do not do so. Mitch Halloran Research (Bio)chemist Duzen Laboratories Group Ankara TURKEY mitch AT duzen DOT com DOT tr other job title: Sequoia's (dob 12-20-95) daddy