1

In the following program, why is text3 empty?

I'd expect it to be "Text3" since I do a strcpy on it inside the param function.

The program

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

void param(char* texte3)
{
      texte3 = malloc(strlen("Text3") + 1);
      strcpy(texte3, "Text3");
}

void param_allocated(char* texte4)
{
      strcpy(texte4, "Text4");
}

int main()
{
    char* text3 = NULL;
    param(text3);
    printf("text 3 %s\n", text3);
    free(text3);

    char* text4 = malloc(strlen("Text4") + 1);
    param_allocated(text4);
    printf("text 4 %s\n", text4);
    free(text4);
}

The output

text 2 Text2
text 3
text 4 Text4

Etsitpab Nioliv
  • 354
  • 1
  • 4
  • 15
  • You need to pass the addres of the pointer `param(&text3);`and change the function protoype to `void param(char** texte3)`, otherwise the `malloc` will only affect the local variable – David Ranieri Mar 11 '20 at 11:46
  • @Lundin I indeed looked for a duplicate like this, but it is hard to find with the keywords mentioned in the title "Dynamic memory access only works inside function". Could perhaps be improved to include the keywords "pointer" and "assignment" somehow – Ctx Mar 11 '20 at 12:02
  • @Ctx It's a community wiki, feel free to edit :) Though you can find lots of canonical dupes from [C tag wiki](https://stackoverflow.com/tags/c/info) FAQ, this one sitting under "dynamic memory allocation". – Lundin Mar 11 '20 at 12:03
  • @Lundin Yes, but at least I wouldn't have recognized from the title that the content of "Dynamic memory access only works inside function" matches the situation of the OP. But ok, maybe it's just me... – Ctx Mar 11 '20 at 12:07
  • texte3 is a different variable from text3. – user253751 Mar 11 '20 at 13:04

1 Answers1

3

In this line

texte3 = malloc(strlen("Text3") + 1);

you only modify the local variable texte3. If you want to modify the variable text3 in the caller, you have to pass a pointer to this variable to param()

param(&text3);

change the function declaration to take a pointer to a pointer

void param(char** texte3)

and dereference the passed (double-)pointer on assignment/usage:

*texte3 = malloc(strlen("Text3") + 1);
strcpy(*texte3, "Text3");

Note, that the above two statements can be written more briefly as

*texte3 = strdup("Text3");

Then it should work as you expect.

Ctx
  • 18,090
  • 24
  • 36
  • 51