lkml.org 
[lkml]   [2022]   [Mar]   [21]   [last100]   RSS Feed
Views: [wrap][no wrap]   [headers]  [forward] 
 
Messages in this thread
/
Date
From
SubjectRe: [RFC PATCH v1 6/6] tools/include/string: Implement `strdup()` and `strndup()`
On 3/21/22 2:53 PM, Willy Tarreau wrote:
> Hi Ammar,
[...]
>> +static void free(void *ptr);
>> +static void *malloc(size_t len);
>> +static void *realloc(void *old_ptr, size_t new_size);
>
> Better include the required h files here.

I can't do that, in nolibc.h, we have something like this:

```
#include "stdlib.h" <--- We inlcude string.h from here
#include "string.h" <--- This is a no-op.
```

Note, stdlib.h is included first before string.h, next, in stdlib.h, we
have this:

```
#include "string.h"

// malloc, calloc, free here
```

If I include "stdlib.h" in "string.h", it will just be a no-op, and the
declarations will not be taken, because the declarations happen after
#include "string.h". So it doesn't work. It's somewhat circular dependency.

stdlib.h needs string.h
string.h needs stdlib.h

One of them must fully see the other before they can use the defined functions
in another header.

Suggestion welcome...

I am thinking of creating a new header just for the forward declarations
where all function declarations live there, we just split off the real
functions' body.

[...]
>
> This version is suboptimal in terms of code size, CPU usage and memory
> usage. And it even seems it contains a buffer overflow: if the string
> is exactly a multiple of 2048, it seems to me that you'll write the
> trailing zero past the end. Please instead use the more intuitive form
> below (not tested but you get the idea):
>
> size_t len = strlen(str);
> char *ret = malloc(len + 1);
> if (ret)
> memcpy(ret, str, len);
> return ret;

Ah right, that's indeed overflow. Will fold this in as you suggested.

[...]
> Here it can cost quite a lot for large values of maxlen. Please just use
> a variant of the proposal above like this one:
>
> size_t len;
> char *ret;
>
> len = strlen(str);
> if (len > maxlen)
> len = maxlen;
> ret = malloc(len + 1);
> if (ret)
> memcpy(ret, str, len);
> return ret;

Will take the Alviro's suggestion for this part...

--
Ammar Faizi

\
 
 \ /
  Last update: 2022-03-21 12:39    [W:0.090 / U:0.388 seconds]
©2003-2020 Jasper Spaans|hosted at Digital Ocean and TransIP|Read the blog|Advertise on this site