Re: Nulls get converted to 0 problem - Mailing list pgsql-general

From Jon Earle
Subject Re: Nulls get converted to 0 problem
Date
Msg-id Pine.LNX.4.55.0306061100400.19934@kronos.honk.org
Whole thread Raw
In response to Re: Nulls get converted to 0 problem  (kdebisschop@alert.infoplease.com)
Responses Re: Nulls get converted to 0 problem  (DeJuan Jackson <djackson@speedfc.com>)
List pgsql-general
On Fri, 6 Jun 2003, Karl DeBisschop wrote:

> Perhaps because the SQL Spec says they are different?
>
> For that matter, a zero length string in C is not the same as NULL.
> Believing otherwise may be convenient, but leads to segfaults

Only if you mistreat them, as in your first example.  Testing strings is a
must:

main() {
  char *str1;
  char *str2 = "";
  char *str3 = "test";

  // Check if str1 is valid
  // Since str1 was not set to anything, it _could_ be valid.  It _should_
  // be set to NULL if not initted with data, as in: char *str1 = NULL;
  if (!str1) printf("This is not a valid string.\n");

  // More correct check for str1.
  if (str1 && !*str1)
    printf("This is a better check for str1's validity\n");

  // Check if str2 contains data.
  if (str2 && !*str2) printf("This is also not a valid string.\n");

  // If str3 is valid and contains data
  if (str3 && *str3) printf("This is a valid string\n");

  // Set the start of str3 to null.
  *str3 = 0;

  // If str3 is valid and doesn't contain data
  if (str3 && !*str3) printf("This is not a valid string\n");
}

But that doesn't answer the question that, what is the difference between
no data and null?  They both indicate zero value.  There's some esoteric
difference that I'm missing, probably because my programming background
has not involved database work until very recently.

Cheers!
Jon

>
> i.e., this code will cause a segfault
>
> main(...) {
>   char *str;
>
>   if (str == NULL)
>     printf ("This test is safe\n");
>
>   if (str == "")
>     printf ("This comparison above can segfault on some systems\n");
>
>   printf ("printing a NULL string like %s can also segfault\n", str);
>
> }
>
> I believe in C the following is true as well:

No. See above.

>
> main() {
>   char *str="";
>
>   if (str)
>     printf ("An empty string evaluates as true");
>
> }
>
> --
> Karl DeBisschop <kdebisschop@alert.infoplease.com>
>

--
Jon Earle

SAVE FARSCAPE http://www.savefarscape.com/

pgsql-general by date:

Previous
From: Oleg Bartunov
Date:
Subject: Re: Create index on the year of a date column
Next
From: Tom Lane
Date:
Subject: Re: Create index on the year of a date column