- this is the same
No, it is not.
char * test1() {
char * returnValue = "test";
return returnValue;
}
The code above returns a fixed address in a constant literal "test"
. This will be the same address every time the function is called.
This is not a dynamic memory allocation.
Performance
printf("%d\n", test1() == test1());
will print
1
True, the two returned addresses match.
In "constness"
To better reflect the constancy of the result test1()
, it is better to define it as follows:
const char * test1() {
const char * returnValue = "test";
return returnValue;
}
char * test2 {
char * returnValue = strdup("test");
return returnValue;
}
, "test"
. * 1 .
* 1: "-", test2() ()
. free()
, strdup()
( malloc()
), , .
printf("%d\n", test2() == test2()); /* leaks memory: 2 times 4+1 char */
0
"false", .
: ,
char * p, * q;
printf("%d\n", (p = test2()) == (q = test2()));
free(p);
free(q);
.
, , "" , .