nunos
nunos

Reputation: 21409

How to test is a string is initialized in c?

Quick and easy C question: char* foo

How can I test if foo hasn't still been assigned a value?

Thanks.

Upvotes: 3

Views: 3296

Answers (3)

Steve Jessop
Steve Jessop

Reputation: 279345

You can't test at runtime in a platform-independent way. Doing anything with an uninitialized value other than assigning to it is undefined behaviour. Look at the source and analyse the code flow.

It may be that your compiler initialises stack memory with a particular value, and you could test for this value. It's not portable even to the same compiler with different flags (because the standard doesn't require it, and it might only happen in debug mode), and it's not reliable because you might have assigned the "magic" value.

What you'd normally do in this case is initialize the pointer to NULL (equivalently, 0), then later test whether it is NULL. This doesn't tell you whether you've assigned NULL to it or not in the intervening time, but it tells you whether you've assigned a "useful" value.

Upvotes: 7

Brian R. Bondy
Brian R. Bondy

Reputation: 347476

Your variable is defined/declared just not initialized. You can check if your variable has a value by first initializing it when you declare it. Then later you can check if it has that initial value.

char *foo = NULL;


//...

if(foo)
{
}

Upvotes: 0

ptomato
ptomato

Reputation: 57920

You can't.

Instead, initialize it with NULL and check whether it is NULL:

char *foo = NULL;
...
if(!foo) { /* shorter way of saying if(foo == NULL) */

Upvotes: 28

Related Questions