Crashes after printing elements

-2

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;
}
c
arrays
asked on Stack Overflow Feb 8, 2018 by dxerok • edited Feb 8, 2018 by Vardit

2 Answers

4

change

pDreptunghi = (Dreptunghi*)malloc(n+1);

to

pDreptunghi = malloc( (sizeof(*pDreptunghi)*n) + 1);
answered on Stack Overflow Feb 8, 2018 by Martin Chekurov
0

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);

answered on Stack Overflow Feb 8, 2018 by Paresh Dhandhukiya

User contributions licensed under CC BY-SA 3.0