Q:

I'm using malloc and my program is crashing

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!

A:

name = malloc(sizeof(int));

is the problem. That way you can store only one int in the array. Try
name = malloc(sizeof(int) * 500);

instead.

A:

Uh, "malloc()" isn't crashing your program.
You're crashing your program :)
SUGGESTIONS:

Check for "name=malloc()" returning NULL (i.e. check for errors).
Don't allocate space for 1 int ("sizeof(int)" is probably four bytes), then try to write 500 ints :)
Don't litter your code with "magic numbers" like "500" - use a constant instead.

SUGGESTED CHANGES:
#include<stdio.h>
#include<stdlib.h>

#define NELMS 500

int main(){

    int *name = NULL,x;
    char y;
    name=malloc(sizeof(int) * NELMS);
    if (!name) {
      perror ("Unable to allocate memory!");
      return 1;
    }
    for(x=0;x<NELMS;x++){
        name[x]=x;
    }
    for(x=0;x<NELMS;x++){
        printf("%d ",name[x]);
    }

    scanf("%c",&y);
    free(name);
    return 0;
}

A:

You are allocating memory to store only one int. What you need is:
name=malloc(500*sizeof(int));

