Comment by dmitrygr
Comment by dmitrygr 5 days ago
Lucky for us C programmers. Each distro provides its own trusted libc, and my code has no other dependencies. :)
Comment by dmitrygr 5 days ago
Lucky for us C programmers. Each distro provides its own trusted libc, and my code has no other dependencies. :)
C (actually POSIX) has a hashmap implementation: https://man7.org/linux/man-pages/man3/hsearch.3.html
What it doesn't have is a hashmap type, but in C types are cheap and are created on an ad-hoc basis. As long as it corresponds to the correct interface, you can declare the type anyway you like.
char *
left_pad (const char * string, unsigned int pad)
{
char tmp[strlen (string)+pad+1];
memset (tmp, ' ', pad);
strcpy (tmp+pad, string);
return strdup (tmp);
}
Doesn't sound too hard in my opinion. This only works for strings, that fit on the stack, so if you want to make it robust, you should check for the string size. It (like everything in C) can of course fail. Also it is a quite naive implementation, since it calculates the string size three times.Not a C expert but you’re using a dynamic array right on the stack, and then returning the duplicate of that. Shouldn’t that be Malloc’ed instead?? Is it safe to return the duplicate of a stack allocated array, wouldn’t the copy be heap allocated anyway? Not to mention it blows the stack and you get segmentation fault?
> and then returning the duplicate of that. Shouldn’t that be Malloc’ed instead??
Like the sibling already wrote, that's what strdup does.
> Is it safe to return the duplicate of a stack allocated
Yeah sure, it's a copy.
> wouldn’t the copy be heap allocated anyway?
Yes. I wouldn't commit it like that, it is a naive implementation. But honestly I wouldn't commit leftpad at all, it doesn't sound like a sensible abstraction boundary to me.
> Not to mention it blows the stack and you get segmentation fault?
Yes and I already mentioned that in my comment.
---
> dynamic array right on the stack
Nitpick: It's a variable length array and it is auto allocated. Dynamic allocation refers to the heap or something similar, not already done by the compiler.
strdup allocates
strndup would be safer if I correctly recall from my C days?
Safer for what? That opinion seems to be misguided to me.
strndup prevents you from overrunning the allocation of a string given that you pass it the containing allocations size correctly. But if you got passed something that is not a string, there will be a buffer overrun right there in the first line. Also what outer allocation?
You use strcpy when you get a string and memcpy when you get an array of char. strncpy is for when you get something that is maybe a string, but also a limited array. There ARE use cases for it, but it isn't for safety.
Do you rewrite fundamental data structures over and over, like maps, of just not use them?