C: non-NUL terminated array of chars - c

I saw here that it isn't possible to find out a (unsigned char *) string length using strlen if it isn't NULL terminated, since the strlen function will go over the string but won't find any '\0', hence a run-time error. I figure that it is exactly the same for string declared with signed char *.
I saw a code snippet that was doing something like int len = sizeof(unsigned char *); but, as I understand, it only gives the size of a pointer - word size. Is it possible to use sizeof in another way to get the result or do I have to get the length somewhere else?

Yes, you have to get the length from somewhere else. A pointer does not include length information and without a convention (e.g. last element is 0), there is no way to tell how long the array is.

non-NUL terminated string
No such thing in C. In C, by definition a string always ends with a null character.
A string is a contiguous sequence of characters terminated by and including the first null character. C11 ยง7.1.1 1
A string is not a pointer. A pointer may point to a string. See below for limitations.
unsigned char *s, signed char *s or char *s are all character pointers. They may contain the address of some character or have a value like NULL. As OP recognizes, sizeof s is the size of the pointer and not the size of the string.
sizeof() can be use to find the size of a string when code uses sizeof some_array_variable. The length will be 1 less than the size is select situations.
strlen() can always be used to find the length of a string. But not all arrays are strings, nor do all character pointers point to a string. See below.
char b[] below is an array and sizeof b will return 6, the size of the array in char units. When b, the formal argument, is passed to strlen(), it is converted to the address of the first element of b and strlen() uses that as its actual argument. strlen() uses that address to find the length. The length of the string is the count of characters, but not inducing the null character '\0', so the result is 5.
char *t below is a pointer assigned the address of the first character to b. Its size, system dependent, is the size of a pointer like 4,8,2, etc. strlen() uses that address like above and the result is 5.
char b[] = "Hello";
char *t = b;
printf("%zu %zu\n", sizeof b, strlen(b)); // 6 5
printf("%zu %zu\n", sizeof t, strlen(t)); // 4 5
Below, in both lines, strlen() is a problem as that function expects a pointer to a string. Instead, it receives a pointer to the beginning of a character array (size 5) that does not contain a null character. The result is undefined behavior. Code may return 5, it may return 100, it may crash the program, it may report differently tomorrow.
char d[5] = "Hello";
char *u = d;
printf("%zu %zu\n", sizeof d, strlen(d)); // 5 *
printf("%zu %zu\n", sizeof u, strlen(u)); // 4 *
In this example, the size of the array is 100, yet the string length is 5. So using sizeof(e) to find the string length does not return a +1 different answer than strlen(e).
char e[100] = "Hello";
char *v = e;
printf("%zu %zu\n", sizeof e, strlen(e)); // 100 5
printf("%zu %zu\n", sizeof v, strlen(v)); // 4 5

Related

Maybe a "malloc()" issue : Server to Visitor message is flaw [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
C: differences between pointer and array
Different sizeof results
Basically, I did this...
char *str1 = "Sanjeev";
char str2[] = "Sanjeev";
printf("%d %d\n",strlen(str1),sizeof(str1));
printf("%d %d\n",strlen(str2),sizeof(str2));
and my output was
7 4
7 8
I'm not able to give reasons as to why the sizeof str1 is 4. Please explain the difference between these.
Because sizeof gives you the size in bytes of the data type. The data type of str1 is char* which 4 bytes. In contrast, strlen gives you the length of the string in chars not including the null terminator, thus 7. The sizeof str2 is char array of 8 bytes, which is the number of chars including the null terminator.
See this entry from the C-FAQ: http://c-faq.com/~scs/cclass/krnotes/sx9d.html
Try this:
char str2[8];
strncpy(str2, "Sanjeev", 7);
char *str1 = str2;
printf("%d %d\n",strlen(str1),sizeof(str1));
printf("%d %d\n",strlen(str2),sizeof(str2));
str1 is a pointer to char and size of a pointer variable on your system is 4.
str2 is a array of char on stack, which stores 8 characters, "s","a","n","j","e","e","v","\0" so its size is 8
Important to note that size of pointer to various data type will be same, because they are pointing to different data types but they occupy only size of pointer on that system.
sizeof(str1) is sizeof(char*)
whereas sizeof str2 is sizeof(char array)
sizeof(char array) should be equal to strlen(char array) + 1 (NULL termination).
Well if you pass the char array to a function, its size as shown by sizeof will change. The reason is char array is passed as char* only.
char *str1 = "Sanjeev";
printf("%d %d\n",strlen(str1),sizeof(str1));
strlen() gives the length of the string which is 7. sizeof() is a compile time operator and sizeof(str1) gives the size of pointer on your implementation (i.e 4).
char str2[] = "Sanjeev";
printf("%d %d\n",strlen(str2),sizeof(str2));
sizeof(str2) gives the size of the array which is 8*sizeof(char) i.e. 8 [including the NUL terminator]

Getting wrong string length

I am trying to get the length of a string but i am getting the wrong value, it is saying that it is only 4 characters long. Why is this? am i using sizeof() correctly?
#include <stdio.h>
int main(void)
{
char *s;
int len;
s = "hello world";
len = sizeof(s);
printf("%d\n", len);
}
The sizeof operator is returning the size of the pointer. If you want the length of a string, use the strlen function.
Even if you had an array (e.g. char s[] = "hello world") the sizeof operator would return the wrong value, as it would return the length of the array which includes the string terminator character.
Oh and as a side note, if you want a string pointer to point to literal string, you should declare it const char *, as string literals are constant and can't be modified.
You have declared s as a pointer. When applied to a pointer, sizeof() returns the size of the pointer, not the size of the element pointed to. On your system, the size of a pointer to char happens to be four bytes. So you will see 4 as your output.
In addition to strlen(), you can assign string literal to array of chars
char s[] = "hello world", in this case sizeof() returns size of array in bytes. In this particular case 12, one extra byte for \0 character at the end of the string.
Runtime complexity of sizeof() is O(1).
Complexity of strlen() is O(n).

For any string "char name[10]="test"",is strlen(name)+1 always guaranteed to be same as sizeof(name)?

For a string name[],can we use strlen(name)+1 and sizeof(name) interchangeably in our code without second thought?Aren't they same?I checked about it and found out even the return type for both is same,size_t.And after all sizeof calculates the size as a multiple of bytes and a character occupies one byte, while strlen() calculates the number of characters excluding the \0 due to which we have to add a 1 to equate it to the result of sizeof.
So unless the size of the character is something other than 1 byte,aren't the two interchangeable and same for all practical purposes?Like while allocating dynamic memory for example....
For a declared array like char name[10], sizeof(name) is the size of the entire array, regardless of what data is stored in it. strlen(name) returns the number of characters in the array before the first 0. Behavior of strlen is undefined if there aren't any zeros in the array.
Which book are you reading? sizeof is an operator that tells you how many bytes a type (or in your case, the type of an object) occupies. strlen is a function that tells you where the first '\0' character is located, which indicates the end of the string.
char foo[32] = "hello";
printf("sizeof foo: %zu\n", sizeof foo);
printf("strlen(foo): %zu\n", strlen(foo));
sizeof foo is 32 regardless of what you store in foo, but as you can see strlen(foo) is in fact 5, where you would expect the '\0' (NUL-terminator) to go.
In terms of dynamic allocation, you can expect to store the return value of malloc in a pointer.
char *foo = malloc(32);
strcpy(foo, "hello");
printf("sizeof foo: %zu\n", sizeof foo);
printf("sizeof (char *): %zu\n", sizeof (char *));
printf("strlen(foo): %zu\n", strlen(foo));
In this case, sizeof foo is sizeof (char *), because it gives you the number of bytes in a char * (pointer to char). This is very different to the strlen function because the size of a pointer to char is constant during runtime.
sizeof (char) is always 1. That's required by the C standard. If you find an implementation where that isn't the case, then it isn't a C implementation.
Perhaps your book might explain this, which is why I asked... but there are plenty of poor quality books. Please do answer that question!

How to get the string size in bytes?

As the title implies, my question is how to get the size of a string in C. Is it good to use sizeof if I've declared it (the string) in a function without malloc in it? Or, if I've declared it as a pointer? What if I initialized it with malloc? I would like to have an exhaustive response.
You can use strlen. Size is determined by the terminating null-character, so passed string should be valid.
If you want to get size of memory buffer, that contains your string, and you have pointer to it:
If it is dynamic array(created with malloc), it is impossible to get
it size, since compiler doesn't know what pointer is pointing at.
(check this)
If it is static array, you can use sizeof to get its size.
If you are confused about difference between dynamic and static arrays, check this.
Use strlen to get the length of a null-terminated string.
sizeof returns the length of the array not the string. If it's a pointer (char *s), not an array (char s[]), it won't work, since it will return the size of the pointer (usually 4 bytes on 32-bit systems). I believe an array will be passed or returned as a pointer, so you'd lose the ability to use sizeof to check the size of the array.
So, only if the string spans the entire array (e.g. char s[] = "stuff"), would using sizeof for a statically defined array return what you want (and be faster as it wouldn't need to loop through to find the null-terminator) (if the last character is a null-terminator, you will need to subtract 1). If it doesn't span the entire array, it won't return what you want.
An alternative to all this is actually storing the size of the string.
While sizeof works for this specific type of string:
char str[] = "content";
int charcount = sizeof str - 1; // -1 to exclude terminating '\0'
It does not work if str is pointer (sizeof returns size of pointer, usually 4 or 8) or array with specified length (sizeof will return the byte count matching specified length, which for char type are same).
Just use strlen().
If you use sizeof()then a char *str and char str[] will return different answers. char str[] will return the length of the string(including the string terminator) while char *str will return the size of the pointer(differs as per compiler).
I like to use:
(strlen(string) + 1 ) * sizeof(char)
This will give you the buffer size in bytes. You can use this with snprintf() may help:
const char* message = "%s, World!";
char* string = (char*)malloc((strlen(message)+1))*sizeof(char));
snprintf(string, (strlen(message)+1))*sizeof(char), message, "Hello");
Cheers! Function: size_t strlen (const char *s)
There are two ways of finding the string size bytes:
1st Solution:
# include <iostream>
# include <cctype>
# include <cstring>
using namespace std;
int main()
{
char str[] = {"A lonely day."};
cout<<"The string bytes for str[] is: "<<strlen(str);
return 0;
}
2nd Solution:
# include <iostream>
# include <cstring>
using namespace std;
int main()
{
char str[] = {"A lonely day."};
cout<<"The string bytes for str[] is: "<<sizeof(str);
return 0;
}
Both solution produces different outputs. I will explain it to you after you read these.
The 1st solution uses strlen and based on cplusplus.com,
The length of a C string is determined by the terminating null-character: A C string is as long as the number of characters between the beginning of the string and the terminating null character (without including the terminating null character itself).
That can explain why does the 1st Solution prints out the correct string size bytes when the 2nd Solution prints the wrong string size bytes. But if you still don't understand, then continue reading.
The 2nd Solution uses sizeof to find out the string size bytes. Based on this SO answer, it says (modified it):
sizeof("f") must return 2 string size bytes, one for the 'f' and one for the terminating '\0' (terminating null-character).
That is why the output is string size bytes 14. One for the whole string and one for '\0'.
Conclusion:
To get the correct answer for 2nd Solution, you must do sizeof(str)-1.
References:
Sizeof string literal
https://cplusplus.com/reference/cstring/strlen/?kw=strlen

Another way for string creation in C? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C -> sizeof string is always 8
I found the following way to create a string:
#include <stdio.h>
#include <string.h>
int main(void) {
char *ptr = "this is a short string";
int count = sizeof ptr / sizeof ptr[0];
int count2 = strlen(ptr);
printf("the size of array is %d\n", count);
printf("the size of array is %d\n", count2);
return 0;
}
I can't use the the usual way to get the length by sizeof ptr / sizeof ptr[0], Does this way to create string is valid? Any pros and cons about his notation?
When you do this
char *ptr = "this is a short string";
ptr is actually a pointer on the stack.
Which points to string literal on the readonly memory.
[ptr] ----> "This is a short string"
So trying to get the sizeof ptr will always evaluate to size of int on that particular
machine.
But when you try this
char ptr[]="this is a short string";
Then actually for whole string the memory is created on the stack with ptr having
starting address of the array
|t|h|i|s| |i|s| | |a| |s|h|o|r|t| |s|t|r|i|n|g|\0|
|' '| ==> this is atually a byte shown in above diagram and ptr keep the address of |t|.
So size of ptr will give you the size of whole array.
Because ptr is a pointer and not an array. If you used char ptr[] instead of char *ptr, you would have gotten an almost-correct result - instead of 22, it would have resulted in 23, since the size of the array incorporates the terminating NUL byte also, which is not counted by strlen().
By the way, "creating" a string like this is (almost) valid, but if you don't use a character array, the compiler will initialize the pointer with the address of an array of constant strings, so you should really write
`const char *ptr`
instead of what you have now (i. e. add the const qualifier).
Yes, using strlen to get the size of a string is valid. Even more, strlen is the proper way to get the size of a string. The sizeof solution here is even wrong. sizeof ptr will return 8 on 64 bits system because it is the size of a pointer, divided by the size of a char, which is 1, you will obtain only 8.
The only case where you can use sizeof to get the size of a string is when it is declared as an array of character (char[]).
This code will crash if you modify the string (because recent compilers see it as a constant). Besides, it gives incorrect results as sizeof(ptr) returns the pointer size rather than the string size.
You should rather write:
char ptr[] = "this is a short string";
Because this code will let you find the sctring length as well as modify the string contents.

Resources