Copy a gchar explication

Hi guys

Someone can take a doubt:

const gchar * text = “Some text”;
const gchar * copy;

copy = text;

And:

const gchar * text = “Some text”;
const gchar * copy;

copy = g_strdup (text);

The first code copies the address and the second the content. Is this right?

First of all, never use const char* for the return value of g_strdup(); the g_strdup() function allocates memory, and you need to pass the returned value to g_free() to free the allocated resources.

Yes:

const char *foo = "Some text";
const char *bar = foo;

declares two variables, foo pointing to a static string; and bar, pointing to foo.

const char *foo = "Some text";
char *bar = g_strdup (foo);

declares two variables: foo, pointing to a static string; and bar, pointing to a string that contains a copy of the contents of foo.

This is a basic C question; I’m sure you can find an explanation on StackOverflow, or any other C programming language resources.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.