Samuel
Samuel

Reputation: 6237

Is a local constant string in global memory

Is I define a global pointer(char*). Then give an address of a constant string. Is this address will be freeed. for example:

static char *str;    
const char * test()
{
    str = "hello world";
    return str;
}

Q1: Now is it safe to use the content of the address get by test anywhere.
Q2: If the test is in a DLL. Is it safe to use out side by other program
Q3: If it's safe . When I reassign another const string to variable str. Will the old const string be freeed

Upvotes: 2

Views: 537

Answers (4)

Ricky Stewart
Ricky Stewart

Reputation: 1142

It's safe if you assign a string literal to the pointer, but if you're going to do that it seems like it would be best to leave the function out of the picture entirely:

static char str[] = "hello world";

Then you could just use str like a static char * since arrays just decay to pointers.

Upvotes: 0

Bill Lynch
Bill Lynch

Reputation: 81926

If you do the following, you can use the result of foo() anywhere. You should not modify or free it however. It is irrelevant if this code is part of a DLL or a Library.

const char * foo() {
    return "hello";
}

// This is identical.
const char * foo() {
    const char *x = "hello";
    return x;
}

If you want to be able to modify, you could do something like this. Note that every call to foo() will be referring to the same piece of memory because x is static. Note that here, you can modify x, but you still should not free it.

char * foo() {
    static char x[] = "hello";
    return x;
}

If you wanted to be able to free the result of foo(), you must allocate the space with malloc().

Upvotes: 1

Mankarse
Mankarse

Reputation: 40613

The assignment to str isn't even necessary. Even without it, it would be safe to return the address of a string literal from a function and to subsequently use the string anywhere.

Upvotes: 0

TieDad
TieDad

Reputation: 9889

If only from code perspective, this is safe. But you should make sure in test(), you can only assign a string const to str. If you do like following:

const char *test() {
  char somestr[somesize];
  str = somestr;
  return str;
}

That's still not safe.

Upvotes: 1

Related Questions