Why C cannot run this program for large array sizes?
When I run this program for large array sizes (e.g. 100000) the following error appears: "General Protection" and the run in halted at line 8 (i.e. c[i]=0;). I wondered if you help me in "How should I modify the following program in order to run"?
#include <stdlib.h>
float *c;
void main()
{开发者_StackOverflow
long i;
c=(float*) malloc (sizeof(float*)*100000);
for (i=0;i<100000;i++)
c[i]=0;
}
Try this:
int main(){
float *c = malloc(sizeof(float) * 100000);
for (int i=0; i<100000; i++)
c[i]=0;
return 0;
}
Edit: I use some C99 features here, and only run for compilers who treats int
as 32 bit or 64 bit. This should run with gcc on linux or Mac OS X.
This should be:
c=(float*) malloc (sizeof(float)*100000);
I think you are using a 16 bit compiler and that malloc
can't allocate that much memory in a single contiguous block.
I've just noticed that you are using long
as your loop variable rather than the more commonly used int
which further backs up my wild guess.
float c;
This is a float, not an array. You probably mean:
float *c;
c=(float) malloc (sizeof(float*)*100000);
This attempts to cast an array of floats as a float. Again, you probably mean:
c = (float*) malloc (sizeof(float)*100000);
精彩评论