Right now, I am studying a Yale course.
One of the snippets is:
char *
strdup(const char *s)
{
char *s2;
s2 = malloc(strlen(s)+1);
if(s2 != 0) {
strcpy(s2, s);
}
return s2;
}
If I understand correctly, we need a malloc()
here since we are copying the string s
into another string s2
and so we need to allocate enough space to s2
. However, when I tried out the following code:
#include <stdio.h>
int main(void) {
// your code goes here
char *str = "Test";
printf("%s", str);
return 0;
}
here, it gives me the correct and expected output.
So, I have two questions:
Is
malloc()
needed in the first snippet because we needs2
to be an array?Am I invoking UB in the second snippet, (because I have no where declared
*str
to be pointing to an array)? And we need an array because in C, a string is stored as a character array.