4 ms·
I get strtok and strcat, but what's wrong with strdup?
by fullstop 4y ago
I get strtok and strcat, but what's wrong with strdup?
- jstimpfle 4y agoIt's only very marginally useful, strdup(x) is equivalent to malloc(strlen(x)). It is one of the few functions that allocate, but it doesn't have "alloc" in its name, putting more of an onus on the programmer to free() appropriately. Also, it's advocating bad programming style. Just mallocing random small things all over the place is not how you structure programs well. (Instead, most strings should be in a pool or in another context that is more local than the malloc() heap, so individual strings can be released at once without having to track all the strings attached to a million different structures).
- fullstop 4y agoOther POSIX functions, such as glob, also allocate memory and don't have alloc in the name. It's something that I use. Maybe not frequently, but I definitely use it. Also, it is in no way equivalent to malloc(strlen(x)). You're off by one byte and you've not copied any of the string.
- jstimpfle 4y agoOops, see how my mind became lazy when thinking about such a boring, tasteless function? A function like memdup() would be slightly more useful. At least, glob() has its own globfree() function, leaving room for slightly more mindful organization.
- fullstop 4y agoYou can't even do strcpy(malloc(strlen(x)+1), x) because it doesn't check that malloc succeeded. strdup does all of this for you! :-)
- kayamon 4y agoMaybe your mind would become more engaged if you took the time to understand how the functions worked properly.
- jstimpfle 4y agoI do of course understand how this "works".
- kayamon 4y ago> strdup(x) is equivalent to malloc(strlen(x))
- jstimpfle 4y agoDude. Have you ever typed or said total nonsense because your mind was already busy with the next, more interesting thing?
- kayamon 4y agoIf things frequently seem nonsense to you perhaps greater reading comprehension skills may help you keep up with busy-minded folk.
- jstimpfle 4y agoWhat are you up to? I made a fairly clear and simple point but you seem to be hung up on a stupid "typo". And what do you allude to with regards to reading comprehension?
- kayamon 4y agoIf you frequently make stupid typos perhaps you may enjoy writing lessons to go with the reading comprehension ones.