LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   realloc () : invalid pointer error (https://www.linuxquestions.org/questions/linux-newbie-8/realloc-invalid-pointer-error-4175671477/)

Rishabhh Rawat 03-17-2020 12:55 AM

realloc () : invalid pointer error
 
Question;-

Today, I write a program on realloc() in visual studio code.

Input;-

#include<stdio.h>
#include<stdlib.h>
void main()
{
int n,b;
int *ptr;
int *p,*q;
int i,c=0;
printf("\nEnter the size of array = ");
scanf("%d",&n);
ptr = (int*)malloc(n*sizeof(int));
if(ptr==NULL)
{
printf("Error,its envolved");
exit(0);
}
p = ptr;
printf("\n\nEnter Element in block;-\n\n");
for(i=0;i<n;i++)
{
scanf("%d",ptr);
c = c + *ptr;
ptr++;
}
printf("\nSum = %d\n",c);
printf("\nElements in Block;-\n\n");
for(i=0;i<n;i++)
{
printf("\n%d",*p);
p++;
}
printf("\nNew size of array = ");
scanf("%d",&b);
ptr = (int*)realloc(ptr,b*sizeof(int));
if(ptr==NULL)
{
printf("Error,its envolved");
exit(0);
}
q = ptr;
printf("\n\nEnter Element in block;-\n\n");
for(i=0;i<b;i++)
{
scanf("%d",ptr);
c = c + *ptr;
ptr++;
}
printf("\nSum = %d\n",c);
printf("\nElements in Block;-\n\n");
for(i=0;i<b;i++)
{
printf("\n%d",*q);
q++;
}

}

output;-

realloc(): invalid pointer
Aborted (core dumped)


{DEAR SIR/MAM, HOW CAN I FIX THIS? }

pan64 03-17-2020 01:12 AM

first of all you need to use code tags to post your code, that will keep the original formatting. It is now quite hard to read.

berndbausch 03-17-2020 02:15 AM

I had submitted a great answer, but then I found I misunderstood your program.

Yes, please use code tags.

berndbausch 03-17-2020 02:24 AM

Quote:

Originally Posted by Rishabhh Rawat (Post 6101380)
for(i=0;i<n;i++)
{
scanf("%d",ptr);
c = c + *ptr;
ptr++;
}

realloc(): invalid pointer
Aborted (core dumped)


{DEAR SIR/MAM, HOW CAN I FIX THIS? }

You move the pointer after the end of the allocated region, if I understand your program right. Since nothing is allocated there, the pointer is invalid.

Troubleshooting advice: Find the most recent location in the program where the pointer is set.


All times are GMT -5. The time now is 12:42 PM.