TomG
TomG

Reputation: 2529

How to use the free function on int* pointers in C

This is my code:

int size;
int *p1;
scanf("%d",&size);
p1 =(int*)malloc(sizeof(int)*(size-1));         
for (i=0;i<size;i++)
    scanf("%d",&p1[i]);
free(p1);

The program runs perfectly until the last line - the free function. when it gets to it, i get a huge error window something like " HEAP CORRUPTION DETECTED".

i know that free function should get a void pointer, but mine is int. how can i free it?

thanks!

Upvotes: 1

Views: 9819

Answers (2)

Daniel Fischer
Daniel Fischer

Reputation: 183918

You are scanning in one more number than you have allocated space for

p1 =(int*)malloc(sizeof(int)*(size-1));         
for (i=0;i<size;i++)

that causes the corruption, malloc size * sizeof *p1 bytes.

The call to free is correct.

Upvotes: 5

user1944441
user1944441

Reputation:

p1 =(int*)malloc(sizeof(int)*(size-1));  

should be

p1 =(int*)malloc(sizeof(int)*(size));  

You allocated memory for size-1 number of integers but you want to read size number of them

Upvotes: 2

Related Questions