How can I check if a string is initialized in c?

Quick and easy C question: char* foo

How to check if foo

no value has been assigned yet?

Thanks.

+2


a source to share


3 answers


You can not.

Instead, initialize it with NULL

and check if it is there NULL

:



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

      

+26


a source


You cannot test at runtime regardless of platform. Doing anything with an uninitialized value other than assigning it to it is undefined behavior. Look at the source and analyze the code flow.

Perhaps your compiler is initializing stack memory to a specific value and you can check that value. It does not even carry over to the same compiler with different flags (since the standard does not require it, and this can only happen in debug mode), and it is not reliable because you might have assigned a "magic" value.



What you usually do in this case is to initialize the pointer to NULL

(equivalent to, 0) and then check if that is NULL

. It doesn't tell you whether you've been assigned NULL or not in the span of time, but it does tell you if you've been assigned a "useful" value.

+7


a source


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

char *foo = NULL;


//...

if(foo)
{
}

      

0


a source







All Articles