My program crashes at runtime with the following error:
"Exception thrown at 0x777433D5 (ntdll.dll) in caza.exe: 0xC0000005: Access violation reading location 0x00000003."
What went wrong?
I've tried with that free function at main and without it and experienced the same error.
#include <stdio.h>
#include <malloc.h>
typedef struct Dreptunghi
{
int x1, y1, x2, y2;
}Dreptunghi;
void readElements(Dreptunghi* pDreptunghi, int nDreptunghi)
{
for (int i = 0; i < nDreptunghi; ++i)
{
printf("Introduceti valorile pentru dreptunghiul %d \n", i + 1);
scanf("%d %d %d %d",
&pDreptunghi[i].x1,
&pDreptunghi[i].y1,
&pDreptunghi[i].x2,
&pDreptunghi[i].y2);
}
printf("\n");
}
void printElements(Dreptunghi* pDreptunghi, int nDreptunghi)
{
for (int i = 0; i < nDreptunghi; ++i)
{
printf("%d %d %d %d\n",
pDreptunghi[i].x1,
pDreptunghi[i].y1,
pDreptunghi[i].x2,
pDreptunghi[i].y2);
}
}
int main()
{
Dreptunghi* pDreptunghi = NULL;
int n=0;
scanf("%d", &n);
pDreptunghi = (Dreptunghi*)malloc(n+1);
readElements(pDreptunghi, n);
printElements(pDreptunghi, n);
free(pDreptunghi);
return 0;
}
change
pDreptunghi = (Dreptunghi*)malloc(n+1);
to
pDreptunghi = malloc( (sizeof(*pDreptunghi)*n) + 1);
you are not allocating enough memory here ,you need to assign memory that equals size of structure multiply by number of element :
pDreptunghi = (Dreptunghi*)malloc((sizeof(*pDreptunghi)*n)+1);
User contributions licensed under CC BY-SA 3.0