|
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] Re: [Xen-devel] [PATCH V2 3/6] [RFC] xen/common: Introduce _xrealloc function
Hi Jan,
Jan Beulich writes:
> On 02.08.2019 18:39, Oleksandr Tyshchenko wrote:
>> --- a/xen/common/xmalloc_tlsf.c
>> +++ b/xen/common/xmalloc_tlsf.c
>> @@ -610,6 +610,27 @@ void *_xzalloc(unsigned long size, unsigned long align)
>> return p ? memset(p, 0, size) : p;
>> }
>>
>> +void *_xrealloc(void *p, unsigned long new_size, unsigned long align)
>> +{
>> + void *new_p;
>> +
>> + if ( !new_size )
>> + {
>> + xfree(p);
>> + return NULL;
>> + }
>> +
>> + new_p = _xmalloc(new_size, align);
>> +
>> + if ( new_p && p )
>> + {
>> + memcpy(new_p, p, new_size);
>> + xfree(p);
>> + }
>> +
>> + return new_p;
>> +}
>
> While I can see why having a re-allocation function may be handy,
> explicit / direct use of _xmalloc() and _xzalloc() are discouraged,
> in favor of the more type-safe underscore-less variants. I can't
> see though how a type-safe "realloc" could look like, except for
> arrays. If resizing arrays is all you're after, I'd like to
> recommend to go that route rather then the suggested one here. If
> resizing arbitrary objects is the goal, then what you suggest may
> be the only route, but I'd still be not overly happy to see such
> added.
I can see 3 uses for realloc:
a. re-allocate generic data buffer
b. re-allocate array
c. re-allocate struct with flexible buffer.
option c. is about structures like this:
struct arrlen
{
size_t len;
int data[1];
};
This is Oleksandr's case.
So for option a. we can use _xreallocate(ptr, size, align)
For option b. we can use xrealloc_array(_ptr, _type, _num)
And for option c. I propose to implement the following macro:
#define realloc_flex_struct(_ptr, _type, _field, _len) \
((_type *)_xrealloc(_ptr, offsetof(_type, _field[_len]) , __alignof__(_type)))
It can be used in the following way:
newptr = realloc_flex_struct(ptr, struct arrlen, newsize);
As you can see, this approach is type-safe and covers Oleksanrd's case.
--
Volodymyr Babchuk at EPAM
_______________________________________________
Xen-devel mailing list
Xen-devel@xxxxxxxxxxxxxxxxxxxx
https://lists.xenproject.org/mailman/listinfo/xen-devel
|
![]() |
Lists.xenproject.org is hosted with RackSpace, monitoring our |