MoMoe0 MoMoe0 - 1 month ago 5
C Question

Functions with pointer to pointer and strcpy

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void Get_Text(char *string);
void Get_Text_Double(char **string);
void String_Copy(char *string);

int main(void) {
char *name = malloc(10 * sizeof(char));
char *name2 = malloc(10 * sizeof(char));
char *name3 = malloc(10 * sizeof(char));

Get_Text(name);
printf("\n%s\n", name);

Get_Text_Double(&name2);
printf("\n%s\n", name2);

String_Copy(name3);
printf("\n%s\n", name3);

return 0;
}

void Get_Text(char *string) {
string = "test";
}

void Get_Text_Double(char **string) {
*string = "test2";
}

void String_Copy(char *string) {
strcpy(string, "test3");
}


In the above code, why do the
Get_Text_Double
and
String_Copy
functions work and the
Get_Text
function does not?

Also why does the
String_Copy
function work only with a single pointer instead of a double pointer like
Get_Text_Double
?

Answer

The Get_Text function does not work, because it only changes the copy of the pointer that was passed to it. After the function exits, it is lost. The = operator cannot copy a string anyway, only the value of the pointer. And so the line

printf("\n%s\n", name);

causes undefined behaviour because the memory allocated to name has not been initialised.

In the next function Get_Text_Double the location of the pointer was passed. This is replaced by a pointer to a string literal, overwriting the pointer that was obtained from malloc. So it will now not be possible to free(name2).

In the last function String_Copy the library function strcpy was used to copy the string literal into the memory that was obtained for name3.

The last function is the only one of the three, that actually copies a string into the memory provided. The other two only copy the pointer to a string, being lost in the first example.

Comments