0

Page 143 of the K&R book implements a function that makes a copy of a string s:

// Make a duplicate of s
char *strdup(char *s)
{
    char *p;
    
    p = (char *) malloc(strlen(s) + 1); // +1 for '\0'
    if (p != NULL)
       strcpy(p, s);
    return p;
}

Is that best practice? That is, don't use strcpy directly; instead, do a malloc and then do a strcpy into the newly malloc'ed space.

What is the danger of using strcpy directly?

IrAM
  • 1,720
  • 5
  • 18
Roger Costello
  • 3,007
  • 1
  • 22
  • 43
  • 1
    I think K&R illustrating [`strdup`](https://man7.org/linux/man-pages/man3/strdup.3.html) function, not suggesting how to use `strcpy` there – IrAM Feb 14 '21 at 13:00
  • @Roger Costello It is unclear what you mean. – Vlad from Moscow Feb 14 '21 at 13:02
  • 2
    It's not clear what the alternative you're suggesting is by "using strcpy directly". Into what memory? – Paul Hankin Feb 14 '21 at 13:03
  • Without malloc you will be using wild pointer which is Undefined Behaviour. – 0___________ Feb 14 '21 at 13:04
  • While I agree with the idea of closing this question (either because it's unclear or because "best practice" is usually opinionated), I see no way in which it's a dupe of https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior – Paul Hankin Feb 14 '21 at 13:08
  • @PaulHankin using of an uninitialized pointer is Undefined Behaviour. What is UB is in that link. (Best practice)There is no "best practice" of using wild pointers. So it cannot be answered or adviced) – 0___________ Feb 14 '21 at 13:10
  • 1
    You can only use memory which was allocated somehow. Just defining a pointer does not reserve any memory for the referenced object. You need to do it yourself – 0___________ Feb 14 '21 at 13:15
  • The safety issue with this code is that `strlen` is at risk of reading memory that isn't before a `null` character. That means this code could theoretically run forever. Using `strcpy` in this case isn't a safety issue, because if you get to that line of code, the buffer is guaranteed to be large enough to receive the copy. People who don't know _why_ `strcpy` is unsafe, and just say "unsafe" when they see `strcpy`. The reason it is unsafe is because it can copy outside of the desired memory, changing other variables. That can't happen if you allocate enough ram to receive the copy. – Edwin Buck Feb 14 '21 at 17:32

0 Answers0