0

How do I correctly allocate heap memory in a function so its caller can use the pointer passed in? For example:

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

void test(char *arg) {
    arg = malloc(3);
    strcpy(arg,"hi");
}

int main() {
    char *x = NULL;
    test(x);
    printf("%s\n",x); //should print "hi", instead does nothing
    return 0;
}

I have also tried to use strdup but cannot get main to correctly print the string I assign the pointer to in the test function, but I always get garbage data or a segfault.

To be clear, I cannot modify the signature of test in any way, so double pointers or returning a pointer are not valid solutions. It is possible to return a different string using a char* argument?)

bjubes
  • 195
  • 1
  • 15
  • I cannot use the solutions marked as duplicates because they require changing the function signature to pass a string using **char or by returning a char pointer. – bjubes Nov 26 '19 at 22:55
  • 1
    It’s impossible. You have no way of communicating the new memory address back to the caller short of using global state. – nneonneo Nov 26 '19 at 22:57
  • 1
    Don't pass ```NULL```. allocate at main(), and pass it, don't allocate in test(), copy string.. Simple, Hah ??!! – Peter Lee Nov 26 '19 at 23:08
  • 1
    if you can't change the signature of `test`, then it's a useless function. Everything in C is pass by value, so the only way to modify an argument _and_ have that modification persist outside the scope of the function is by returning it, or passing in the address and dereferencing it in the function to modify it. `x` and `arg` are 2 different variables with 2 different addresses. Modifying `arg` in `test` has no bearing on `x` any more than if their types were `int`. All `test` does here is create a memory leak. – yano Nov 26 '19 at 23:31

0 Answers0