tags:

views:

228

answers:

2

Hi everybody

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.

A: 

One of three things are true:

Either: 1) g_array_append_val is making a copy of the string.

Or: 2) as soon as the stack is overwritten again, things will break.

void burn_stack(int size)
{
   char data[8]={0,0,0,0,0,0,0,0};
   size-=8;
   if (size>0) burn_stack(size);
}

Try calling burn_stack(256); after function_name, and see if things continue to work.

Or: 3) You're using const char "string"s, which are stored in the string section of the executable, and not on the heap nor the stack, hence they will persist indefinitely.

Dave Gamble
Incorrect - those string constants have static storage duration, so they are not likely to be stored on the stack. The pointers to them probably are, but that's not a problem here.
caf
Ah of course, they're constants. My bad.
Dave Gamble
+1  A: 

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:

function_name (garray, "arg2", "arg3" /* and so on ... */);

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).

caf
you said 'object with static storage duration is created', i don't knew that, thnx caf, this explain my doubt! ;D
drigoSkalWalker