Article View: att.lang.c++
Article #262Re: The brother pointer gives me a headache
From: Chuck McCorvey
Date: Tue, 17 Feb 1998 00:00
Date: Tue, 17 Feb 1998 00:00
84 lines
2546 bytes
2546 bytes
AlexV <alexvak@hotmail.com> wrote in article
<01bd3b40$c55acd50$a080fac3@johnpanoid>...
> /*
> Would you please tell me why am i getting an error message in VC:
>
> Unhandled in MyArrayTest.exe 0x0000005: Access Violation
>
> please look down to see where the error appears
>
> */
>
> #include <stdio.h>
> #include <stdlib.h>
> #include <process.h>
> #include <time.h>
>
> int main() {
> char charin;
> long counter;
> long i;
> long *num;
> long sumnum;
> int j;
>
> sumnum = 0;
> counter = 0;
>
> cout << "Wait..."
>
> if ((num = (long *) malloc(10000000)) == NULL)
> {
> printf("Not enough memory to allocate buffer\n");
> cin >> counter;
> exit(1);
> }
>
>
> j = 0;
> for (i = 0; i < 10000000; i++ ) {
> if ( i % 100 == 0 ){
> *(num + i) = 38;
> }
> else {
> /************** HERE IT IS ************/
> *(num + i) = 50; // it gives me an errors when i = 2119943
> /************* END HERE IT IS ********/
> if ( i > 2299000 & i < 2320000)
> cout << i << "\n";
> }
> }
>
> cout << "Finished putting values in memory,\n\n Press enter to calculate
> the average: ";
> cin >> charin;
>
> counter = 0;
> for (i = 0; i < 10000000; i++ ) {
> sumnum = sumnum + *(num + i);
> counter++;
> }
> free(num);
>
> cout << "\n\n\nAverage is " << sumnum / i;
> cin >> charin;
>
>
> return 0;
> }
>
Your troubles are due to allocating 10,000,000 bytes and treating the
resulting block of memory as an array of 10,000,000 long integers. The
array of longs is generally 4 times as large as the memory block you
allocated.
If you mean to have 10,000,000 longs, do this
num = (long*) malloc(malloc10000000);
Better still, if you are really doing C++, you should use operator new. So
use:
num = new long[10000000];
Technical Details
Message-ID:
<01bd3b49$06457ab0$056464c0@server>Path:
arc1-ca.pugleaf.net!unknown!not-for-mailReferences:
<01bd3b40$c55acd50$a080fac3@johnpanoid>Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: 109fba,7b57483de3649335 X-Google-Attributes: gid109fba,public X-Google-Thread: 108b44,7b57483de3649335 X-Google-Attributes: gid108b44,public X-Google-Thread: 10d4ba,7b57483de3649335 X-Google-Attributes: gid10d4ba,public From: "Chuck McCorvey" <chuckm@solutionware.com> Subject: Re: The brother pointer gives me a headache Date: 1998/02/17 Message-ID: <01bd3b49$06457ab0$056464c0@server> X-Deja-AN: 325733902 References: <01bd3b40$c55acd50$a080fac3@johnpanoid> Organization: Creative SolutionWare, Inc. Newsgroups: att.lang.c++,comp.lang.c++,comp.sys.lang.c++