I’m learning C using the book C Programming: A Modern
Approach and I have some doubts about the use of pointers
and referencing an out-of-scope variables. I’ve put together three examples to
illustrate my doubts.
-
First, we have this:
char *f() { char p[] = "Hi, I'm a string"; return p; }
It is my understanding that this code is problematic because
p
is a variable of type
array ofchars
local to the scope of the functionf()
. When I returnp
, I’m using
the name of the array as a pointer to the first element, but since the variable is only
valid inside the function scope, when I returnp
, I end up with a pointer to a
variable that is not valid (a dangling pointer?). As a result, if I try to usep
outside the function, I get a segmentation fault.Is this correct?
-
Next I have this:
char *g() { char *p = "Hi, I'm a string"; return p; }
This is very close to the previous case, but it seems to be ok, I can access the string
from outside the function and I don’t get a warning from the compiler (as I did in the
previous case). I don’t understand why it works though,p
is declared as achar
pointer, so I’d assume that, when it’s initialized, it points to the first char in the
string literal, the same as when it as an array, is that not the case, or is it actually
undefiled behavior that works out in my specific context? -
Finally, I have this:
char *h() { char *p = malloc(17 * sizeof(char)); strcpy(p, "Hi, I'm a string"); return p; }
Is this somehow different from the previous example? I assume it’s not, I’m just
allocating the memory manually. This also seems to let me access the entire string from
outside the function, but I have the same doubts as with the previous example.
I tested the three functions this way:
int main(int argc, char *argv[]) {
// This causes a segmentation fault
printf("%sn", f());
// These two work ok
printf("%sn", g());
printf("%sn", h());
}
Can you help me better understand what’s going on here?
Thanks in advance!