[PATCH v2 01/50] lib: Add memdup()

Sean Anderson sean.anderson at seco.com
Thu May 6 19:57:31 CEST 2021



On 5/6/21 1:41 PM, Simon Glass wrote:
 > Hi Pratyush,
 >
 > On Thu, 6 May 2021 at 10:07, Pratyush Yadav <p.yadav at ti.com> wrote:
 >>
 >> On 06/05/21 08:23AM, Simon Glass wrote:
 >>> Add a function to duplicate a memory region, a little like strdup().
 >>>
 >>> Signed-off-by: Simon Glass <sjg at chromium.org>
 >>> ---
 >>>
 >>> Changes in v2:
 >>> - Add a patch to introduce a memdup() function
 >>>
 >>>   include/linux/string.h | 13 +++++++++++++
 >>>   lib/string.c           | 13 +++++++++++++
 >>>   test/lib/string.c      | 32 ++++++++++++++++++++++++++++++++
 >>>   3 files changed, 58 insertions(+)
 >>>
 >>> diff --git a/include/linux/string.h b/include/linux/string.h
 >>> index dd255f21633..3169c93796e 100644
 >>> --- a/include/linux/string.h
 >>> +++ b/include/linux/string.h
 >>> @@ -129,6 +129,19 @@ extern void * memchr(const void *,int,__kernel_size_t);
 >>>   void *memchr_inv(const void *, int, size_t);
 >>>   #endif
 >>>
 >>> +/**
 >>> + * memdup() - allocate a buffer and copy in the contents
 >>> + *
 >>> + * Note that this returns a valid pointer even if @len is 0
 >>
 >> I'm uneducated about U-Boot's memory allocator. But I wonder how it
 >> returns a valid pointer even on 0 length allocations. What location does
 >> it point to? What are users expected to do with that pointer? They
 >> obviously can't read/write to it since it is supposed to be a 0 byte
 >> long allocation. If another positive length allocation happens before
 >> the said pointer is freed, will it point to the same memory location? If
 >> not, isn't the 0-length pointer actually at least a 1-length pointer?
 >
 > I think it is just a 0-length pointer and that the only thing you can
 > do with it is call free().
 >
 > I am certainly no expert on this sort of thing though. It seems that
 > some implementations return NULL for a zero size, some return a valid
 > pointer which can be passed to free(). Of course, U-Boot lets you pass
 > NULL to free() anyway.

dlmalloc has a minimum allocation size of 2*sizeof(void *) (e.g.
MINSIZE - 2*SIZE_SZ). If you request less than this, you will get an
allocation of this size. This is the same as other requests, which are
rounded up the the nearest multiple of MALLOC_ALIGNMENT. Of course,
malloc_simple will actually give you a zero-byte allocation, so don't
rely on being able to store anything there ;)

--Sean


More information about the U-Boot mailing list