Can you please tell me what I did wrong?
#include <stdio.h>
#include <stdlib.h>
void read(int *p,int n)
{
int *q,i,j;
q=p;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
printf("matrix[%d][%d]=",i,j);
scanf("%d",q);
q=q+1;
}
printf("\n");
}
void alocate(int *p,int n)
{
p=(int*)malloc(n*n*sizeof(int));
if(p==NULL)
{
printf("Allocation error\n");
exit(1);
}
}
void realocate(int *p,int n)
{
p=(int*)realloc(p,n*n*sizeof(int));
if(p==NULL)
{
printf("Reallocation error\n");
exit(1);
}
}
void show(int *p,int n)
{
int *q,i,j;
q=p;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",*q);
q=q+1;
}
printf("\n");
}
}
void cleaner(int *p)
{
free(p);
}
int main() {
int *p,n;
p=NULL;
printf("n=");
scanf("%d",&n);
alocate(p,n);
read(p,n);
show(p,n);
realocate(p,2);
read(p,2);
show(p,2);
cleaner(p);
return 0;
system("pause");
}
NetBeans (MinGW):
RUN FAILED (exit value 5)
Signal received: SIGSEGV (?) with sigcode ? (?)
From process: ?
For program cppapplication_1, pid -1
Visual Studio:
Unhandled exception at 0x5c81e42e (msvcr100d.dll) in Capp.exe: 0xC0000005: Access violation writing location 0x00000000.
And if I delete p=NULL; from main function, it says:
Run-Time Check Failure #3 – The variable ‘p’ is being used without being initialized.
Unhandled exception at 0x5b4ee42e (msvcr100d.dll) in Capp.exe: 0xC0000005: Access violation writing location 0xcccccccc.
Your
alocatefunction correctly allocates memory, but does not return a pointer to the allocated memory. You can fix it like thisIn your
mainfunction, you would usealocatelike this:You need to make a similar change to your
realocatefunction.