I have a program that call a function with undefined arguments, like this:
#include <stdargs.h>
... /* code */
int main () {
GArray *garray = g_array_new (FALSE, FALSE, sizeof (char *));
/* the code above initialize the GArray, and say that the garray expect a pointer to char. */
function_name (garray, "arg2", "arg3" /* and so on ... */);
... /* code */
}
note that, the args between ” ” are strings, so, in the function_name:
static void function_name (GArray *garray, ...) {
... /* code */
char *data;
data = va_arg (garray, gchar *);
g_array_append_val (garray, data);
... /* code */
}
So, if data points to a argument in va_list, when the function return, teorically the data pointed, turn to be invalidated, and in garray too.
(causing a dangling reference, because data pointer, points to a memory adress not reserved more).
but its not appear to happen, the program runs well. why? and, in C, arguments passed to functions are stored in stack, so, data points life in stack indeed memory?
thnkx a lot.
When you introduce a string constant in a C program, an unnamed, unmodifiable, object with static storage duration is created. “Static storage duration” means it lives for the life of the program.
So when you have this in your code:
The strings “arg2” and “arg3” are string constants – they exist somewhere in program memory, for the life of the program. Often these are stored in a text segment, in the same way that the program code itself is.
What is actually passed to function_name() – presumably on the stack – are pointers to those string constants. And that is what your GArray ends up storing – pointers to those string constants.
(Note that a string used as an array initialiser is not a string constant).