Passing not null terminated string to printf results in unexpected value - c

This C program gives a weird result:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
char str1[5] = "abcde";
char str2[5] = " haha";
printf("%s\n", str1);
return 0;
}
when I run this code I get:
abcde haha
I only want to print the first string as can be seen from the code.
Why does it print both of them?

"abcde" is actually 6 bytes long because of the null terminating character in C strings. When you do this:
char str1[5] = "abcde";
You aren't storing the null terminating character so it is not a proper string.
When you do this:
char str1[5] = "abcde";
char str2[5] = " haha";
printf("%s\n", str1);
It just happens to be that the second string is stored right after the first, although this is not required. By calling printf on a string that isn't null terminated you have already caused undefined behavior.
Update:
As stated in the comments by clcto this can be avoided by not explicitly specifying the size of the array and letting the compiler determine it based off of the string:
char str1[] = "abcde";
or use a pointer instead if that works for your use case, although they are not the same:
const char *str1 = "abcde";

Both strings str1 and str2 are not null terminated. Therefore the statement
printf("%s\n", str1);
will invoke undefined behavior.
printf prints the characters in a string one by one until it encounters a '\0' which is not present in your string. In this case printf continues past the end of the string until it finds a null character somewhere in the memory. In your case it seems that printf past the end of string "abcde" and continues to print the characters from second string " haha" which is by chance located just after first string in the memory.
Better to change the block
char str1[5] = "abcde";
char str2[5] = " haha";
to
char str1[] = "abcde";
char str2[] = " haha";
to avoid this problem.

Technically, this behavior is not unexpected, it is undefined: your code is passing a pointer to a C string that lacks null terminator to printf, which is undefined behavior.
In your case, though, it happens that the compiler places two strings back-to-back in memory, so printf runs into null terminator after printing str2, which explains the result that you get.
If you would like to print only the first string, add space for null terminator, like this:
char str1[6] = "abcde";
Better yet, let the compiler compute the correct size for you:
char str1[] = "abcde";

You have invoked undefined behaviour. Here:
char str1[5] = "abcde";
str1 has space for the above five letters but no null terminator.
Then the way you try to pass not null terminated string to printf for printing, invokes undefined behaviour.
In general in most of the cases it is not good idea to pass not null terminated strings to standard functions which expect (C) strings.

In C such declarations
char str1[5] = "abcde";
are allowed. In fact there are 6 initializers because the string literal includes the terminating zero. However in the left side there is declared a character array that has only 5 elements. So it does not include the terminating zero.
It looks like
char str1[5] = { 'a', 'b', 'c', 'd', 'e', '\0' };
If you would compile this declaration in C++ then the compiler issues an error.
It would be better to declare the array without specifying explicitly its size.
char str1[] = "abcde";
In this case it would have the size equal to the number of characters in the string literal including the terminating zero that is equal to 6. And you can write
printf("%s\n", str1);
Otherwise the function continues to print characters beyond the array until it meets the zero character.
Nevertheless it is not an error. Simply you should correctly specify the format specifier in the call of printf:
printf("%5.5s\n", str1);
and you will get the expected result.

The %s specifier searches for a null termination. Therefore you need to add '\0' to the end of your string
char str1[6] = "abcde\0";

Related

Does directly assigning a string of char's to a char pointer on initialization automatically add a null terminator?

For example in this code:
char *ptr = "string";
Is there a null terminator in the stored in the ptr[6] address?
When I test this and print a string, it prints "string", and if I print the ptr[6] char I get ''. I wanted to test this further so I did some research and found someone saying that strlen will always crash if there is not a null terminator. I ran this in my code and it returned 6, so does this mean that assigning a string to a char pointer initializes with a null terminator or am I misunderstanding what's happening?
Yes. String literals used as pointers will always end in a NUL byte. String literals used as array initializers will too, unless you specify a length that's too small for it to (e.g., char arr[] = "string"; and char arr[7] = "string"; both will, but char arr[6] = "string"; won't).

first character of a string using strncpy bug

I wanted to get the first character of a string using strncpy, here's my code
int main() {
char s[] = "abcdefghi";
char c[] = "";
printf("%c\n",c);
printf("%s\n",s);
strncpy(c,s,1);
printf("%c\n",c);
printf("%s\n",s);
return 0;
}
The problem is that c is still an empty string, what's wrong with it?
The problem is that c is an array (which decays into a pointer), while the %c format of printf() requires a character. If you pass the pointer when the function expects a character, you get undefined behavior, and a possible output will be the first byte of the address of the array, interpreted as an ASCII character.
Also, please note that char c[] = ""; simply declares an array of length 1 which contains the null (\0) character. If you try to print that, like you do in your code, you will likely get weird output.
If c is meant to only store a single character, declare it as a simple char variable, and pass it's address to strncpy():
char s[] = "abcdefghi";
char c = ' ';
printf("%c\n", c);
printf("%s\n", s);
strncpy(&c, s, 1); //notice the & before c
printf("%c\n", c);
printf("%s\n", s);
However, you have to be careful. Passing any value greater than 1 to strncpy() asks for big trouble, since you would be writing to an undefined location.
s is an array of 10 chars, c is an array with one char. Do you understand why? And which char is stored in c?
%s is the format for strings, %c is the format for chars. But c is not a char. An array containing one char is an array, not a char. So when you try to print c you get rubbish.
Now the bad one: strncpy in your case doesn’t produce a C string because there isn’t enough space for one. If you try to print c with %c you get nonsense. If you try to print it with %s you get undefined behaviour. Do NOT use strncpy unless you really know what it is doing (you should generally avoid strncpy).

Character string declaration with static size

I was trying different ways to declare a string in C for exam preparation. We know that string in C is character array with '\0' at end. Then I found that even if I declare an array of 5 characters and put 5 characters in it like "abcde" it is accepted. Then where is the null char stored?
I declared strings in following ways
char str[] = {'a','b','c','d','e'};
char str2[] = "abcde";
char str3[5] = "abcde";
Now, in the 3rd case, I am allocating 5 byte of space and I have exactly 5 characters in the array, then if string should have a null character at end where is it being stored? Or is it the case that null is not appended?
What about the 1st and 2nd cases, are null appended there?
strlen() returns 5 in all 3 cases.
The NUL character is stored only in the second example
char str2[] = "abcde";
where the array is sized automatically to include it. An array of characters does not have to be a string, and the other two are encoded without the NUL terminator.
If the code happens to treat them correctly as strings, that was an unfortunate result of undefined behaviour.
#include <stdio.h>
int main(int argc, char *argv[])
{
char str[] = {'a','b','c','d','e'};
char str2[] = "abcde";
char str3[5] = "abcde";
printf("%zu\n", sizeof str);
printf("%zu\n", sizeof str2);
printf("%zu\n", sizeof str3);
}
Program output:
5
6
5
In the third case, the null terminator is not appended. From the documentation:
If the size of the array is known, it may be one less than the size of
the string literal, in which case the terminating null character is
ignored:
So when you check its length with strlen, you get undefined behavior (and the the same when you try it with the first one, since that also isn't a string).
Any less that that is not allowed, (for me on MSVC it shows an error but still compiles it, for some reason). More than the string length is allowed, in which case the rest is zero-initialized.

Unknown erroneous characters are being added to strings?

I am learning C. Some characters are being added automatically to my program. What am I doing wrong?
#include <stdio.h>
#include <string.h>
int main() {
char test1[2]="xx";
char test2[2]="xx";
printf("test is %s and %s.\n", test1, test2);
return 0;
}
Here is how I am running it on Fedora 20.
gcc -o problem problem.c
./problem
test is xx?}� and xx#.
I would expect the answer would be test is xx and xx.
The issue is that string literals such as "xx" have an extra character that is the nul-termination, \0, that is, it is composed of the characters 'x', 'x' and '\0'.
This is how functions that take char* and treat them as strings know the extent of the strings. Your arrays are simply one element too short, missing the nul-terminator. By passing char* that don't point to a nul-terminated string to a function that expects one, you are invoking undefined behaviour.
You can initialize them like this instead:
char test[] = "xx";
This will result in test having the correct length of 3. You can test that using the sizeof operator. Of course, you can also be explicit about the length:
char test[3] = "xx";
but this is more error-prone.
When you define a String in C like this
char A[] = "hello";
It gets initialized something like this
A = { 'h', 'e', 'l', 'l', 'o', '\0'}
That last null character is needed for the it to be a string. So in your code
char test1[2]="xx";
You have made the test1 character array to be 2 characters long, leaving no space for the null character.
To correct your program, You can either not give the size of the character array, like
char test1[]="xx";
Or, give one more then the characters you are filling in, like
char test1[3]="xx";
In your code char test1[2]="xx", char test1[2] creates a kind a "container" for two chars, but the actual string "xx" implicitly has three chars xx0, where 0 indicates an end of the line. This 0 is an indicator for printf, where it should stop reading the input string. In your case printf doesn't get this 0 as 0 doesn't fit into the test1 and it reads to some random zero in memory, printing everything it meets on the way.
You should change your declaration to the following:
char test1[3]="xx"

Basic C question on copying char arrays to char pointers

I have some doubts in basic C programming.
I have a char array and I have to copy it to a char pointer. So I did the following:
char a[] = {0x3f, 0x4d};
char *p = a;
printf("a = %s\n",a);
printf("p = %s\n",p);
unsigned char str[] = {0x3b, 0x4b};
unsigned char *pstr =str;
memcpy(pstr, str, sizeof str);
printf("str = %s\n",str);
printf("pstr = %s\n",pstr);
My printf statements for pstr and str get appended with the data "a".
If I remove memcpy I get junk. Can some C Guru enlighten me?
Firstly, C strings (the %s in printf) are expected to be NUL-terminated. You're missing the terminators. Try char a[] = {0x3f, 0x4d, 0} (same goes for str).
Secondly, pstr and str point to the same memory, so your memcpy is a no-op. This is a minor point compared to the first one.
Add a null terminator, cause that's what you printf expects:
char a[] = {0x3f, 0x4d, '\0'};
The standard way C strings are represented is that in memory, they are a sequence of non-zero bytes representing the characters, followed by a zero (or NULL) byte. You should declare:
char a[] = {0x3f, 0x4d, 0};
When you assign a string pointer (as in unsigned char *pstr = str;) both pointers point to the same memory area, and thus the same characters. There is no need to copy the characters.
When you do need to copy characters, you should be using strlen(), the sizeof() operator returns the number of bytes its argument uses in memory. sizeof(pointer) is the number of bytes the pointer uses, not the length of the string. You find the length of a string (i.e. the number of bytes it occupies in memory) with the strlen() function. Also, there are standard functions to copy C strings. You should rely on those to do the right thing:
strcpy(pstr, str);
printf's %s expects a 0-terminated string, your strings aren't. The uninitialized memory following your arrays may however happen to start with a 0-byte, in which case your code will appear to be correct - it still isn't.
You're declaring an array "str", then pointing to it with pstr. Note that you have no null-terminating character, so after using memcpy you copy the block to itself with no null terminator, as a string requires. Thus, printf can't find the end of the string and continues printing until it finds a 0 (or '\0' in character terms)
Agreed. You'll have to add a null byte at the end of your array of chars.
char a[] = {0x3f, 0x4d, '\0'};
The reason being is that you're creating a string without declaring where it actually ends. Your memcpy() function copies *str to *pstr and automatically adds a null byte for you, which is why it works.
Without memcpy() there the string never knows when to end, so it reaches into subsequent memory addresses and returns whatever random values are stored there. When you're creating a string out of characters, always remember to end it with a null byte.

Resources