ShowUsYour<Blog>

Irregular expressions regularly

Null Terminator character

A zero Char is added to a char array to indicate its end point, this character is referred to as the "Null Terminator". This character is added to the end of each string to mark its ending boundary - the String classes in .NET do this automagically. So, declaring something like:

    string s = "Foo" ;

Results in the following character array being generated under the covers:

    char[] s = {'F','o','o','0'} ;

This will almost never be a problem because, using .NET string classes and methods which return strings will always return a "safe" string rather than the raw character arrays. But, imagine if that wasn't the case and you had to deal with the "Null Terminator" in your own code; forgetting to do so could easily result in unexpected results:

    Dim a As String = "Foo"
    MsgBox( a )    ' displays "Foo"
    Dim b As String = "Foo" & Chr(0) & "Bar"
    MsgBox( b )    ' displays "Foo"!!!

Yesterday, it did actually bite me because I was dealing with some API calls to get volume information about a machine:

     Private Declare Function GetVolumeInformation Lib "kernel32" Alias "GetVolumeInformationA" _
          (ByVal lpRootPathName As String, _
          ByVal lpVolumeNameBuffer As String, _
          ByVal nVolumeNameSize As Int32, _
          ByRef lpVolumeSerialNumber As System.UInt32, _
          ByRef lpMaximumComponentLength As Int32, _
          ByRef lpFileSystemFlags As Int32, _
          ByVal lpFileSystemNameBuffer As String, _
          ByVal nFileSystemNameSize As Int32) As Int32

     Dim drvserial As System.UInt32
     Dim drvlbl As String = Space(200)
     Dim filesys As String = Space(200)
     Dim i As Int32
     Dim j As Int32
     Dim k As Int32
     k = GetVolumeInformation("C:\", drvlbl, 200, drvserial, i, j, filesys, 200)
     MsgBox( drvserial.ToString & "-" & drvlbl & "-" & filesys )

What happened is that, when I ran this code the value of drvlbl was being returned with the Chr(0) character appended at the end of 200 spaces. Therefore, I was only ever seeing the value or drvserial being displayed. The easy way to fix that - in VB at least - is the use the VB Replace function to clean up the Chr(0) character:

     MsgBox( drvserial.ToString & "-" & Replace( drvlbl, Chr(0), "" ) & "-" & filesys )

I'm not really sure whether this behaviour would be exhibited when making the same API call via C# or whether it's just a "feature" of the VB language; I suspect that it will only be an issue in VB!

Posted: Apr 22 2004, 11:45 AM by digory | with 10 comment(s)
Filed under:

Comments

TrackBack said:

# April 21, 2004 6:10 AM

Justin Rogers said:

The appropriate signature for the method you are calling should be <Out()> StringBuilder or the two string buffers you are using. That'll fix your problem altogether. Then just pass in a string buffer with a pre-planned capacity of 200 for each. You'll also note that some of the other parameters are uint and not int values as you have them in your sample.

In .NET the \0 character can actually be embedded in the middle of a string. That is why internally the String object maintains a length, which is conceptually more important than a null terminating character. Here is some C# code that demonstrates the null character in the middle of a string.

Console.WriteLine("foo\0foo\0foo\0");
# April 21, 2004 9:37 PM

John Layton said:

I've written a few programs in VB6 which write to the registry. I have written another program in C(Win API) which changes these registry settings, but the VB6 programs doesn't recognise the new setting. I know this is to do do with the null terminator. What do you suggest ?
Regards
# June 21, 2004 2:55 PM

Hyma said:

Can i know one example for a null terminator which is used in char data type of ESQL/C ?

# August 23, 2007 12:30 AM

Carattere nullo in una stringa | hilpers said:

Pingback from  Carattere nullo in una stringa | hilpers

# January 18, 2009 8:11 AM

JohnS said:

can anybody tell me if I'm getting an inout from a c++ dll as a result of my request a string having multiple null character then what type should I use so that I can get that whole string along with that null characters in c#

# October 16, 2009 5:45 PM

kikus said:

автор можно узнать вас ICQ для обмена постовыми

# June 13, 2010 5:02 PM

Pupeevetlylit said:

Доброго времени суток,  

Хочу представить вам новоявленный лабаз курительных смесей

сайт магазина http://spice-family.ru  

3г микса Relax - 1,500 р. + доставка (ems, pony set)  

По вопросам опта отмечать поурочно в скайп - FomaX2

# September 2, 2011 11:49 PM

DonaldFR said:

Привет Привет друзья надо что то скачать, но не можете найти здесь есть все что нужно, программы, игры, софт, книги, журналы, фильмы заходим <a href=http://www.alfa-z.info> игры </a>

# September 11, 2011 5:32 PM

DasikK said:

Здравствуйте рекомендую Всем сайт, где оргромный архив ссылок на скаивание кинофильмов, всех жанров и направлений  <a href=http://qi-qi.ru> свежее кино</a> . Ежечасные обновления, старые, документальные, отечественные и зарубежные фильмы всех жанров. Рай для киноманов. Только лучшее для Вас!!!

# September 12, 2011 4:37 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)