Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

null terminating a string

Tags:

c

gcc 4.4.4 c89

What is the standard way to null terminate a string? When I use the NULL I get a warning message.

*dest++ = 0; 
*dest++ = '\0'; 
*dest++ = NULL; /* Warning: Assignment takes integer from pointer without a cast */

Source code:

size_t s_strscpy(char *dest, const char *src, const size_t len)
{
    /* Copy the contents from src to dest */
    size_t i = 0;
    for(i = 0; i < len; i++)
    *dest++ = *src++;

    /* Null terminate dest */
     *dest++ = 0; 

    return i;
}

Another question: I deliberately commented out the line that null terminates. However, it still correctly printed out the contents of the dest. The caller of this function would send the length of the string by either included the NULL or not. i.e. strlen(src) + 1 or stlen(src).

size_t s_strscpy(char *dest, const char *src, const size_t len)
{
    /* Copy the contents from src to dest */
    size_t i = 0;
    /* Don't copy the null terminator */
    for(i = 0; i < len - 1; i++)
    *dest++ = *src++;

    /* Don't add the Null terminator */
    /* *dest++ = 0; */

    return i;
}
like image 358
ant2009 Avatar asked May 26 '10 08:05

ant2009


People also ask

How do you null terminate a string?

The null terminated strings are basically a sequence of characters, and the last element is one null character (denoted by '\0'). When we write some string using double quotes (“…”), then it is converted into null terminated strings by the compiler.

Do strings need to be null-terminated?

The std::string is essentially a vector, in that it is an auto-resizing container for values. It does not need a null terminator since it must keep track of size to know when a resize is needed.

What is a null-terminated sequence?

A null-terminated string is a sequence of ASCII characters, one to a byte, followed by a zero byte (a null byte). null-terminated strings are common in C and C++.


2 Answers

To your first question: I would go with Paul R's comment and terminate with '\0'. But the value 0 itself works also fine. A matter of taste. But don't use the MACRO NULLwhich is meant for pointers.

To your second question: If your string is not terminated with\0, it might still print the expected output because following your string is a non-printable character in your memory. This is a really nasty bug though, since it might blow up when you might not expect it. Always terminate a string with '\0'.

like image 173
Lucas Avatar answered Oct 23 '22 20:10

Lucas


From the comp.lang.c FAQ: http://c-faq.com/null/varieties.html

In essence: NULL (the preprocessor macro for the null pointer) is not the same as NUL (the null character).

like image 19
jamesdlin Avatar answered Oct 23 '22 18:10

jamesdlin