trifork
trifork

Reputation: 57

Check if a string is unallocated

This may be a deeper question than I expect, but can you see if a character pointer is unallocated? For example, a string that is unallocated is not NULL, as seen from when I ran this code:

char *ptr; /* Unallocated char pointer */
if (ptr == NULL) {
        ptr = malloc(10); /* Not casted cause it doesn't matter */
        printf("ptr is allocated\n");
        return(0);
}
printf("ptr is unallocated\n");
return(0);

When I ran the code, I received the message ptr is unallocated. That makes sense because the string could not have memory for a null character. So, is there any way to see if a string is unallocated? Or am I asking the wrong question?

Upvotes: 0

Views: 789

Answers (3)

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158599

There is no way to do this without providing an initial value since unintialized automatic variables will have an indeterminate value. They must be initialized; there is no way to determine the initial value of an automatic variables otherwise. In fact using an uninitialized variable is undefined behavior.

The draft C99 standard says in section 6.7.8 Initialization paragraph 10 says:

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. [...]

and Annex J.2 Undefined behavior paragraph 1 says:

The behavior is undefined in the following circumstances:

and includes the following bullet:

The value of an object with automatic storage duration is used while it is indeterminate (6.2.4, 6.7.8, 6.8).

Upvotes: 2

Yu Hao
Yu Hao

Reputation: 122483

That's because you defined ptr but didn't initialize it. Try this:

char *ptr = NULL;

It's a good coding style to initialize a pointer to a null pointer in general; it is crucial if you want to test whether it is initialized to some valid string.

Upvotes: 2

Greg Hewgill
Greg Hewgill

Reputation: 994231

No, it is not possible. In your case, ptr is uninitialised, which means it might contain any value at all, until the first time you assign something to it. It might be NULL, or it might not.

Upvotes: 4

Related Questions