0

i have the following struct:

typedef struct {
    char* type;
    char* address;
    int area, price;
}Offer;

and these two functions:

Offer* initOffer(char* type, char* address, int area, int price)
{
    Offer* p;
    p = (Offer*)malloc(sizeof(Offer));
    p->type = (char*)malloc(sizeof(type));
    p->address = (char*)malloc(sizeof(address));
    strcpy(p->type, type);
    strcpy(p->address, address);
    p->area = area;
    p->price = price;
    return p;
}

void destroyOffer(Offer* offer)
{
    free(offer->type);
    free(offer->address);
    free(offer);
}

The problem occurs when i call destroyOffer, I have no idea why, but when I run the code, I have an error saying: HEAP CORRUPTION DETECTED. If i remove these 2 lines, it works fine but I suppose that the memory is not cleaned properly:

free(offer->type);
free(offer->address);
J. Newbie
  • 59
  • 9

1 Answers1

0

Problem:

p->type = (char*)malloc(sizeof(type));   // That's just the size of a pointer
p->address = (char*)malloc(sizeof(address)); // Same problem.

After that, the lines:

strcpy(p->type, type);
strcpy(p->address, address);

end up writing over memory they are not supposed to. That leads to undefined behavior.

You need:

p->type = malloc(strlen(type)+1);
p->address = malloc(strlen(address)+1);

See Do I cast the result of malloc?

You can also use strdup if it is supported by your compiler. If so, your code can be simplified to:

p->type = strdup(type);
p->address = strdup(address);
Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270