Today I was messing around with malloc and integer pointer. The program is setup so it allocates a memory location to an integer pointer and then fills the memory location with bunch of integers like an array and then print all the integers. The problem is when ever it finishes running it crashes. And I suspect that malloc is causing the issue.
Here is the code
#include<stdio.h>
#include<stdlib.h>
int main(){
int *name,x;
char y;
name=malloc(sizeof(int));
for(x=0;x<500;x++){
name[x]=x;
}
for(x=0;x<500;x++){
printf("%d ",name[x]);
}
scanf("%c",&y);
free(name);
return 0;
}
please help.
Thanks!
You are allocating memory to store only one
int. What you need is:name=malloc(500*sizeof(int));