-1

I have a few questions regarding string initialization and declaration in C.

Suppose if a I declare a string 's' of size 10 using

char s[10];

Q 1. Is it necessary that all the elements of 's' will be initialized to '\0' or is it just pure luck that I will find other elements to be '\0'?

Q 2. If I instead use malloc to setup a string like this

char *s = malloc(10 * sizeof(char));

Again is it necessary that all the elements will be initialized to '\0'?

Q 3. Further do I need to add an '\0' while declaring the string or not?

char s[10] = "abc";

OR is it has to be

char s[10] = "abc\0";

NOTE: If possible, please take a look at the second answer by Kevin here.

Community
  • 1
  • 1
Lokesh
  • 2,842
  • 7
  • 32
  • 47
  • `"abc"` is equivalent to `'abc\0'`. No, there is no practical reason to initialize every byte to zero if you're just going to be changing it later. You do however want to make sure that the last byte is zero if you plan to pass the starting address to a function that will treat is as null-terminated, such as `printf`, to prevent buffer overrun. – rsethc Oct 09 '14 at 03:54
  • Please create a complete question before you submit it. It is really hard for people to keep up with you changing the question multiple times while they are answering. – Jonathan Leffler Oct 09 '14 at 03:56
  • This question is essentially an amalgamation of two other questions: [String initialization](http://stackoverflow.com/questions/49596/string-initialization) asked by [prakash](http://stackoverflow.com/users/123/prakash) and [String and pointers in C](http://stackoverflow.com/questions/25888220/string-and-pointers-in-c) asked by the OP, [lokesh](http://stackoverflow.com/users/2623749/lokesh). – Jonathan Leffler Oct 09 '14 at 04:08

4 Answers4

1
  1. No — in general. In some contexts yes, though. Specifically, if the variable is a local variable and not static, then it is not initialized at all. If the variable is local and static, or if the variable is file scope and static, or if it is global, then it will be initialized to all bytes zero.

  2. No. malloc() is not guaranteed to return zeroed memory. If you need it zeroed, use calloc() instead.

    These comments apply to any type.

    char s0[10];         // Initialized all bytes zero
    static char s1[10];  // Initialized all bytes zero
    
    void somefunc(void)
    {
        static char s2[10];        // Initialized all bytes zero
        char s3[10];               // Not initialized to all bytes zero
        char *s4 = malloc(10);     // Not initialized to all bytes zero
        char *s5 = calloc(10, 1);  // Initialized all bytes zero
        …code using s0..s5…
    }
    
  3. It is sufficient to use:

    char s6[10] = "abc";     // 3 bytes non-zero plus 7 bytes zero
    

    Writing this would achieve the same result because the size of the array is specified:

    char s7[10] = "abc\0";   // 3 bytes non-zero plus 7 bytes zero
    

    Writing these gives two arrays of different sizes:

    char s8[] = "abc";      // sizeof(s8) == 4 – 1 null byte
    char s9[] = "abc\0";    // sizeof(s9) == 5 – 2 null bytes
    

    C automatically adds a trailing null byte.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • According to the second answer [here](http://stackoverflow.com/questions/49596/string-initialization) by Kevin, its necessary that if a string is initialized with suppose s[10] = "abc" then all the other 7 elements will be set to '\0'. Is it true? – Lokesh Oct 09 '14 at 03:48
  • 1
    Yes; given `char s[10] = "abc";` the first three characters are non-zero and the last seven are all zero bytes. – Jonathan Leffler Oct 09 '14 at 03:51
  • @Lokesh: what is significantly different about your question from those in the one you refer to? Is there a reason not to close this as a duplicate of that. – Jonathan Leffler Oct 09 '14 at 03:55
  • I needed to know if malloc does the same thing i.e does it initializes all elements to '\0'. Further other questions donot clarify that char s[] would initialize other elements to '\0' only if it is initialized to some string i.e char s[10] = "abc" would initialize other elements to '\0' but not char s[10]. I wouldn't have known such things through other questions. Thanks for answering. – Lokesh Oct 09 '14 at 03:58
  • So you should really only have asked Q2 since the other question gives the answers to Q1 and Q3? And what is there new in Q2 of this question that was not told to you in [String and pointers in C](http://stackoverflow.com/questions/25888220/string-and-pointers-in-c)? – Jonathan Leffler Oct 09 '14 at 04:04
  • In the question that you just mentioned I was told that "The contents of a[1] are ill-defined and it seems that, by chance, a[1] did contain a null when you ran your program." which is in contradiction to the answer given by Kevin. Kevin claims that by initializing a string with char a[10] = "abc" all 7 elements are set to '\0' where as the answer to String and pointers in C claims that its just pure luck that I find those 7 elements having '\0'. – Lokesh Oct 09 '14 at 08:42
  • 1
    The contents of `a[1]` are undefined; the data returned by `malloc()` may have any contents at all. The answer given by Kevin has nothing to do with `malloc()` at all; it is dealing with a variable declared as an array. You need to distinguish the cases carefully. When you have `char *ptr = malloc(10);` you can say nothing about the values of any of the bytes in the data pointed at by `ptr`. When you have `char str[10] = "abcdefghi";` you know the value of all the bytes in the array (and also if the initializer string is just `"abc"`). Vastly different bits of code; vastly different behaviour. – Jonathan Leffler Oct 09 '14 at 14:48
1

First and foremost, your s is not a "string". Your s is a character array. The term string refers to the content of a character array. In order to qualify as a string that content must satisfy some requirements. A string is defined as a continuous sequence of characters terminated with a zero character.

Q1. If the array is declared with static storage duration it will begin its life with all zeros in it. In all other cases it will contain unpredictable garbage.

Q2. malloc does not initialize allocated memory. The memory contains unpredictable garbage. calloc allocates character array initialized with zeros.

Q3. What you have on the right-hand side of initialization is called string literal. String literal already includes a terminating zero character implicitly. There's no need to add it explicitly.

However, C language follows the all-or-nothing approach to initialization. If you initialize just a small portion of some aggregate object, the rest of that object is implicitly initialized with zeros. In your case that means that the rest of array s will be filled with zeros anyway all the way to the end. Consequently there's no difference between the end result your two initialization examples. Still, there's no point is specifying that zero character explicitly.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
0

If you declare the string using char s[10]; or malloc, the contents will not be initialized to \0 or anything. It will contain garbage values. So if you need \0 in your string, you need to explicitly store that.

Further, if you do sonething like

char s[10] = "abc";

then, you dont need to add \0,

A note: If you use to calloc instead of malloc to allocate memory, the contents will be initialized to 0.

Haris
  • 12,120
  • 6
  • 43
  • 70
  • Please take a look at the second answer by Kevin [here](http://stackoverflow.com/questions/49596/string-initialization). It states that the array if initialized would store '\0' in all its elements rather than garbage value. Is it true? – Lokesh Oct 09 '14 at 03:51
  • @Lokesh: It says if you do `char str1[32] = "\0"; char str2[32] = "";`, then it will initialized to `0`. not when you do `char s[10];` – Haris Oct 09 '14 at 04:01
0

Q1. If you don't explicitly initialize a local variable then it can contain any values. Often the bytes will just happen to contain zeroes.

But static variables (declared outside any function or prefixed with the static keyword are guaranteed to be initialized to zeroes.

Q2. Again malloc does not clear them memory but it will often happen to be filled with zeroes. To explicitly get zero-filled memory use calloc().

Q3. You don't need to add \0 inside the double-quotes. The string "abc" means 4 bytes are created somewhere containing the 3 characters then a string-terminator (byte with value zero).

Andrew W. Phillips
  • 3,254
  • 1
  • 21
  • 24