a malloc is not working for some reason
I made a data type:
typedef struct Sale_t *Sale;
struct Sale_t
{
int license;
int km_min;
int km_max;
int price;
};
I am creating it with this function:
Sale saleCreate(int license, int km_min, int km_max, int price,List sales)
{
if(saleFind(sales,license)==RENTAL_CAR_ALREADY_ON_SALE)
{
return NULL;
}
if(km_min<0||km_max<=km_min||price<=0)
{
return NULL;
}
Sale salePtr = malloc(sizeof(*salePtr));
if(!salePtr)
{
return NULL;
}
salePtr->license=license;
salePtr->km_min=km_min; //here it crashes
salePtr->km_max=km_max;
salePtr->price=price;
return salePtr;
}
(Don't mind about Sale
and Sale_t
; I'm using a typedef
in a header file so it's not a problem at all.)
After some testing, I have found out that if salePtr->km_min
gets any integer other than 0
, the program cras开发者_高级运维hes.
What causes this? I'm sure it's something to do with malloc()
...
EDIT
i made a similar data type which works PERFECTLY:
typedef struct Car_t *Car;
struct Car_t
{
int license;
char* name;
int price;
int km;
int renterId;
};
Car carCreate(int license, char* name, int price, int km, List cars)
{
if(carFind(cars,license)==RENTAL_CAR_ALREADY_EXISTS)
{
return NULL;
}
if(km<0||price<=0)
{
return NULL;
}
Car carPtr = malloc(sizeof(*carPtr));
if(!carPtr)
{
return NULL;
}
carPtr->km=km;
carPtr->license=license;
carPtr->name=name;
carPtr->price=price;
carPtr->renterId=0;
return carPtr;
}
This is wrong:
Sale salePtr = malloc(sizeof(*salePtr));
Should (probably) be:
Sale *salePtr = malloc(sizeof(Sale));
I say probably because you're using Sale
which you don't define in the code you've pasted, so it may be typedef'd to a pointer type already.
EDIT
Since the OP has typedef'd Sale to Sale_t*, it should look like this:
Sale salePtr = malloc(sizeof(Sale_t));
This line is wrong:
Sale salePtr = malloc(sizeof(*salePtr));
You used an identifier salePtr
, before it was defined (or well, in the definition itself). This should work:
Sale salePtr = malloc(sizeof(*Sale));
However, since we are actually allocating memory for a Sale_t
this seems more logical to me:
Sale salePtr = malloc(sizeof(Sale_t));
Since the OP mentions that
typedef Sale_t* Sale
was used, here is what needs to be done
Use this for alloc
Sale salePtr = (Sale)malloc(sizeof(Sale));
Use this for return
return salePtr;
精彩评论