Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Allocating memory

Status
Not open for further replies.

Beard36

Programmer
Sep 4, 2003
69
GB
I want to read a file of size 478200 bytes into memory as an array, but I've been getting problems when I run the compiled program. General Protection Faults. I've found that it's not to do with loading the file, but I'm not quite sure what it IS to do with. Here's an example that will cause the same error -

#include <stdio.h>

int main()
{
long n;
int *pTerrain;

pTerrain = (int*)malloc(478200);
if (!pTerrain)
{
printf(&quot;Unable to allocate memory.\n&quot;);
return 1;
}

for (n = 0; n < 478200; n++)
{
printf(&quot;n = %ld\n&quot;, n);
pTerrain[n] = 0;
}

return 0;
}


Each time I run this, it drops out at a slightly different value of n (usually around 146500, but not always so high).

Can anyone tell me if I'm making a foolish mistake, because I just can't come up with any ideas. I am a beginner, though, so you'll have to bear with me if you will. Thanks in advance for any help anyone can give me.

Cheers,
Dan Roberts.
 
1. You don't allocate enough memory

pTerrain = (int*)malloc(478200);
should be
pTerrain = malloc(478200 * sizeof(int) );

2. The cast is completely unnecessary in ANSI-C. What it is doing (incorrectly) at this point in your code is masking the fact that you haven't included stdlib.h.

3. When posting code, its preferable to use the [ code ] for formatting (actually, code turns off all formatting), rather than [ i ] for italics.
 
Aaah. Thanks a lot - much appreciated.
And I'll bear in mind your comment about entering code in the future.

Once more - ta.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top