0

I am trying to debug this code. It is not doing the expected.

#define HELLO_WORLD_STRING “hello world”

void f(char* p)
{
    p = (char *)malloc(strlen(HELLO_WORLD_STRING)+1);
    ASSERT(p != NULL);
    strcpy(p, HELLO_WORLD_STRING);
}

void main()
{
    char * p;
    f(p);
    printf(“%s\n”, p);
    free(p);
}

Why is the code in error?

Turbo
  • 77
  • 1
  • 10
  • Because `p = ...` means *nothing* to the caller of `f`. See the duplicate link. Not only is `p` unchanged in `main`, but the memory allocated in `f` is leaked just to rub salt in the wound. – WhozCraig Mar 11 '22 at 00:05
  • @WhozCraig why? I am calling using pointers right? Can you explain using stacks? – Turbo Mar 11 '22 at 00:09
  • @Turbo You never assign `p` a value in `main`, so you pass a garbage value to `f`. Fortunately, `f` ignores the garbage value. But it never returns any value anywhere, so the pointer returned from `malloc` is lost. It may reduce confusion if you use longer variable names and don't give two different variables the same name. You may be getting confused by the fact that two different variables (one local to `main`, the other local to `f`) are both called `p`. That they have the same name does not cause an assignment to one to change the value of the other! – David Schwartz Mar 11 '22 at 00:26
  • If you read the duplicate link you'll see what the problem. – WhozCraig Mar 11 '22 at 00:34
  • @DavidSchwartz What is the right way to correct the code? Thank you. – Turbo Mar 11 '22 at 16:57
  • There is a clear error, but it is best to avoid suggesting the cause/source of error in the question. The answer to the question in the title is "no, it's a different problem", which is a direct but unhelpful answer. – Clifford Mar 11 '22 at 18:34

0 Answers0