954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Program Crashing

#include <stdlib.h>
#include <stdio.h>
#define SIZE 15 
int main()
  {

	  int *a, i;
	  
      a = (int*) malloc(SIZE*sizeof(int));

      for (i=0; i<SIZE; i++)
          *(a + i) = i * i;
      for (i=0; i<SIZE; i++)
          printf("%d\n", *a++);
	  
      
	  free(a);
      return 0;
  }

Why Is My Program Crashing??

SpS
Posting Pro
599 posts since Aug 2005
Reputation Points: 70
Solved Threads: 32
 

the parameter to free() must be the same pointer that was returned by malloc(), calloc() or realloc(). Your program destroyed that pointer in the printf() statement.

Why don't you use array a just like any other array instead of using pointer arithemic

for (i=0; i<SIZE; i++)
          a[i] = i * i;

for (i=0; i<SIZE; i++)
          printf("%d\n", a[i]);
Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

can u correct the previous code

SpS
Posting Pro
599 posts since Aug 2005
Reputation Points: 70
Solved Threads: 32
 

sunny? Um... It's a copy/paste fix.

Drowzee
Posting Whiz in Training
245 posts since Jul 2005
Reputation Points: 22
Solved Threads: 5
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You