const char* a;
how do I make sure that string 'a' is null terminated? when a = "abcd" and I do sizeof(a), I get 4. Does that mean its not null-terminated? if it were, I would have gotten 5 ?
sizeof(a) gives you the size of the pointer, not of the array of characters the pointer points to. It's the same as if you had said sizeof(char*).
You need to use strlen() to compute the length of a null-terminated string (note that the length returned does not include the null terminator, so strlen("abcd") is 4, not 5). Or, you can initialize an array with the string literal:
char a[] = "abcd";
size_t sizeof_a = sizeof(a); // sizeof_a is 5, because 'a' is an array not a pointer
The string literal "abcd" is null terminated; all string literals are null terminated.
You get 4 because that's the size of a pointer on your system. If you want to get the length of a nul terminated string, you want the strlen function in the C standard library.
The problem here is that you are confusing sizeof() which is a compile time operation with the length of a string which is a runtime operation. The reason get 4 back when you run sizeof(a) is that a is a pointer and the typical size of a pointer in C is 4 bytes. In order to get the length of the string use strlen.
For the second question, how to make sure a string is null terminated. The only way to definitively do this is to null terminate the string yourself. Given only a char* there is no way to 100% guarantee it is properly null terminated. Great care must be taken to ensure the the contract between the producer and consumer of the char* is understood as to who terminates the string.
If you are handed a char array which may or may not have null-terminated data in it, there really isn't a good way to check. The best you can do is search for a null character up to a certian specified length (not indefinitely!). But 0 isn't exactly an unusual byte of data to find in an uninitialzed area of memory.
This is one of the many things about C's defacto string standard that many people dislike. Finding the length of a string a client hands you is an O(n) search operation at best, and a segmentation fault at worst.
Another issue of course is that arrays and pointers are interchangable. That means array_name + 2 is the same as &(array_name[2]), and sizeof(a) is sizeof(char*), not the length of the array.
sizeof(a) is sizeof(const char*), the size of the pointer. It is not affected by the contents of a. For that, you want strlen.
Also, all double-quoted string literals like your "abcd" in source code are automatically null terminated.
sizeof(a) returns the size of the const char *a...not the size of what it is pointing to. You can use strlen(a) to gind the length of the null-terminated string and no, the result of strlen does not include the null-terminator.
Related
I want to copy the string “Best School” into a new space in memory, which of these statements can I use to reserve enough space for it
A. malloc(sizeof(“Best School”))
B. malloc(strlen(“Best School”))
C. malloc(11)
D. malloc(12)
E. malloc(sizeof(“Best School”) + 1)
F. malloc(strlen(“Best School”) + 1)
I am still very new to C programming language so I really am not too sure of which works well. But I will love for someone to show me which ones can be used and why they should be used.
Thank you.
Literal strings in C are really arrays, including the null-terminator.
When you use sizeof on a literal string, you get the size of the array, which of course includes the null-terminator inside the array.
So one correct way for a literal string would be sizeof("Best School") (or sizeof "Best School").
You can also use strlen. If you don't have a string literal but another array or a pointer to the first character of the string, then you must use strlen. But now you have to remember that strlen returns the length of the string without the null-terminator. So you need to add one for that.
So another correct way would then be strlen("Best School") + 1.
Using magic numbers is almost never correct.
Use of sizeof id limited to only this one case (string literal). Ti will not work if you will have a pointer referencing the string. Before you start to be more proficient in C language and "feel" the difference between arrays and pointers IMO you should always use strlen
Example:
char *duplicateString(const char *str)
{
char *newstring = malloc(strlen(str) + 1);
if(newstring) strcpy(newstring, str);
return newstring;
}
In this case, sizeof(str) would give the size of the pointer to char (usually 2, 4 or 8) not the the length of the string referenced by the str
My C codes are listed below:
char s="MIDSH"[3];
printf("%d\n",strlen(&s));
The result of running is 2, which is wrong because char s is just an 'S'.
Does anybody know why and how to solve this problem?
That's actually quite an interesting question. Let's break it up:
"MIDSH"[3]
String literals have array types. So the above applies the subscript operator to the array and evaluates to the 4th character 'S'. It then assigns it to the single character variable s.
printf("%d\n",strlen(&s));
Since s is a single character, and not part of an actual string, the behavior is undefined for the above code.
Signature of strlen is:
size_t strlen(const char *s);
/* The strlen() function calculates the
length of the string s, excluding the
terminating null byte ('\0'). */
strlen expects the input const char array is null terminated. But when you pass the address of an auto variable, you can't guarantee this and thus your program has an undefined behavior.
Does anybody know why and how to solve this problem?
sizeof(char) is guaranteed to be 1. So use sizeof or 1.
The statement
printf("%d\n",strlen(&s));
make no sense for the given case. strlen expects a null terminating string, s is of char type and &s need not necessarily point to an string. What you are getting is one the result of undefined behavior of the program.
To get the size of s you can use sizeof operator
printf("%zu\n", sizeof(s));
The strlen function treats its argument as a pointer to a sequence of characters, where the sequence is terminated by the '\0' character.
By passing a pointer to the single character variable s you effectively say that &s is the first character in such a sequence, but it's not. That means strlen will continue to search in memory under false premises and you will have undefined behavior.
when you use
"char s=" you create a new address on the stack for 's',and this address can't be add or reduce!so though you give strlen a char* but it can't find '\0' by add address.All is wrong.
you should use strlen with a address for char which is a array.like:
char* s = "MIDSH";
printf("%d\n", strlen(s)); //print 5
s++;
printf("%d\n", strlen(s)); //print 4
char *a=NULL;
char *s=NULL;
a=(char *)calloc(1,(sizeof(char)));
s=(char *)calloc(1,(sizeof(char)));
a="DATA";
memcpy(s,a,(strlen(a)));
printf("%s",s);
Can you plz tell me why its printing DATA½½½½½½½½■ε■????How to print only DATA?? Thanks
Strings in C are terminated by a zero character value (nul).
strlen returns the number of characters before the zero.
So you are not copying the zero.
printf keeps going, printing whatever is in the memory after s until it hits a zero.
You also are only creating a buffer of size 1, so you are writing data over whatever is after s, and you leak the memory calloc'd to a before you set a to be a literal.
Allocate the memory for s after finding the length of the string, allocating one more byte to include the nul terminator, then copy a into s. You don't need to allocate anything for a as the C runtime looks after storing the literal "DATA".
strlen does only count the chars without the terminator '\0'.
Without this terminator printf does not know the end od the string.
Solution:
memcpy(s,a,(strlen(a)+1));
You are first allocating memory, then throwing that memory away by re-assigning the pointer using a string literal. Your arguments to calloc() also look very wrong.
Also, memcpy() is not a string copying function, it doesn't include the terminator. You should use strcpy().
The best way to print only DATA would seem to be
puts("DATA");
You need to be more clear on what you want to do, to get help with the pointers/allocations/copying.
Your
a="DATA";
trashes the pointer to the allocated memory. It does not copy "DATA" into the memory. Which however would be not enough to store it, since
a=(char *)calloc(1,(sizeof(char)));
allocates a single char. While
memcpy(s,a,(strlen(a)));
copies what is pointed now by a (string literal "DATA") to the memory which is pointed by s. But again, s points to a single char allocated, and copying more than 1 char will overwrite something and results in a bug.
strlen(a) gives you 4 (the length of "DATA") and memcpy copies exactly 4 char. But to know where a string ends, C uses the convention to put a final "null" char ('\0') to its end. So indeed "DATA" is, in memory, 'D' 'A' 'T' 'A' '\0'.
All string related function expect the null byte, and they don't stop printing until they find it.
To copy strings, use instead strcpy (or strncpy), it copies the string with its final null byte too. (strcpy is less "secure" since you can overflow the destination buffer).
But the biggest problem I can see here is that you reserve a single char only for a (and you trash it then) and s, so DATA\0 won't fit anywhere.
You are reserving space for 1 character so you are actually using the memory of some other variable when you are writing "DATA" (which is 4 characters + the trailing \0 to mark the end of the string).
a=(char *)calloc(1,(sizeof(char)));
For this example you would need 5 characters or more:
a=(char *)calloc(5, (sizeof(char)));
You need to store a terminating \0 after that DATA string so printf() will know to stop printing.
You could replace memcpy with strcat:
strcat(s, a);
should do it.
Note, however, that there's a bug earlier on:
calloc(1,sizeof(char))
will only allocate a single byte! That's certainly not enough! Depending on the implementation, your program may or may not crash.
#include<stdio.h>
int main()
{
char a[5]="hello";
puts(a); //prints hello
}
Why does the code compile correctly? We need six places to store "hello", correct?
The C compiler will let you run off the end of arrays, it does no checks of that sort.
The C compiler allows you to explicitly ask for no null terminator.
char a[] = "Hello"; /* adds a terminator implicitly */
char a[6] = "Hello"; /* adds a terminator implicitly */
char a[5] = "Hello"; /* skips it */
Any value smaller than 5 results in an error.
As for why - one possibility is that your strings are of a fixed size, or are being used as buffers of byte values. In these cases you do not need a null terminator.
Best practice is to use char a[] so the compiler can set it to the correct value (including terminator) automatically.
a doesn't contain a null terminated string (extra initializers for fixed size arrays - such as the null terminator in "hello" - are discarded), so the behaviour when a pointer to that array is passed to puts is undefined.
In my experience, a lot of compilers will let you get away with compiling this. It will usually crash at runtime, though (because you don't have a null terminator).
C char array initialization includes the terminating null only if there is room or if the array dimensions are not specified.
You need 6 characters to store "hello" as a null terminated string. But char arrays are not constrained to store nul terminated string, you may need the array for another purpose and forcing an additional nul character in those cases would be pointless.
That is because in C memory management is done manually unlike in java and some other few languages....
The six places you allocated is not checked for during compilation but if you
have to get into filing(I mean storing actually) you are going to have a runtime error becuase the program kept five places in memory(but is expected to hold six) for the characters but the compiler did not check!
"hello" string is kept in read-only memory with 0 in the end. "a" points to this string, this is why the program may work correctly. But I think that generally this is undefined behavior.
It is necessary to see Assembly code generated by compiler to see what happens exactly. If you want to get junk output in this situation, try:
char a[5] = {'h', 'e', 'l', 'l', 'o'}
The C compiler you are using does not check that the string literal fits to the char array. You need 6 characters in the array to fit the literal "Hello" since the literal includes a terminating zero. Modern compilers, such as Visual C++ 2010 do check these things and give you and error.
I have never really done much C but am starting to play around with it. I am writing little snippets like the one below to try to understand the usage and behaviour of key constructs/functions in C. The one below I wrote trying to understand the difference between char* string and char string[] and how then lengths of strings work. Furthermore I wanted to see if sprintf could be used to concatenate two strings and set it into a third string.
What I discovered was that the third string I was using to store the concatenation of the other two had to be set with char string[] syntax or the binary would die with SIGSEGV (Address boundary error). Setting it using the array syntax required a size so I initially started by setting it to the combined size of the other two strings. This seemed to let me perform the concatenation well enough.
Out of curiosity, though, I tried expanding the "concatenated" string to be longer than the size I had allocated. Much to my surprise, it still worked and the string size increased and could be printf'd fine.
My question is: Why does this happen, is it invalid or have risks/drawbacks? Furthermore, why is char str3[length3] valid but char str3[7] causes "SIGABRT (Abort)" when sprintf line tries to execute?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main() {
char* str1 = "Sup";
char* str2 = "Dood";
int length1 = strlen(str1);
int length2 = strlen(str2);
int length3 = length1 + length2;
char str3[length3];
//char str3[7];
printf("%s (length %d)\n", str1, length1); // Sup (length 3)
printf("%s (length %d)\n", str2, length2); // Dood (length 4)
printf("total length: %d\n", length3); // total length: 7
printf("str3 length: %d\n", (int)strlen(str3)); // str3 length: 6
sprintf(str3, "%s<-------------------->%s", str1, str2);
printf("%s\n", str3); // Sup<-------------------->Dood
printf("str3 length after sprintf: %d\n", // str3 length after sprintf: 29
(int)strlen(str3));
}
This line is wrong:
char str3[length3];
You're not taking the terminating zero into account. It should be:
char str3[length3+1];
You're also trying to get the length of str3, while it hasn't been set yet.
In addition, this line:
sprintf(str3, "%s<-------------------->%s", str1, str2);
will overflow the buffer you allocated for str3. Make sure you allocate enough space to hold the complete string, including the terminating zero.
void main() {
char* str1 = "Sup"; // a pointer to the statically allocated sequence of characters {'S', 'u', 'p', '\0' }
char* str2 = "Dood"; // a pointer to the statically allocated sequence of characters {'D', 'o', 'o', 'd', '\0' }
int length1 = strlen(str1); // the length of str1 without the terminating \0 == 3
int length2 = strlen(str2); // the length of str2 without the terminating \0 == 4
int length3 = length1 + length2;
char str3[length3]; // declare an array of7 characters, uninitialized
So far so good. Now:
printf("str3 length: %d\n", (int)strlen(str3)); // What is the length of str3? str3 is uninitialized!
C is a primitive language. It doesn't have strings. What it does have is arrays and pointers. A string is a convention, not a datatype. By convention, people agree that "an array of chars is a string, and the string ends at the first null character". All the C string functions follow this convention, but it is a convention. It is simply assumed that you follow it, or the string functions will break.
So str3 is not a 7-character string. It is an array of 7 characters. If you pass it to a function which expects a string, then that function will look for a '\0' to find the end of the string. str3 was never initialized, so it contains random garbage. In your case, apparently, there was a '\0' after the 6th character so strlen returns 6, but that's not guaranteed. If it hadn't been there, then it would have read past the end of the array.
sprintf(str3, "%s<-------------------->%s", str1, str2);
And here it goes wrong again. You are trying to copy the string "Sup<-------------------->Dood\0" into an array of 7 characters. That won't fit. Of course the C function doesn't know this, it just copies past the end of the array. Undefined behavior, and will probably crash.
printf("%s\n", str3); // Sup<-------------------->Dood
And here you try to print the string stored at str3. printf is a string function. It doesn't care (or know) about the size of your array. It is given a string, and, like all other string functions, determines the length of the string by looking for a '\0'.
Instead of trying to learn C by trial and error, I suggest that you go to your local bookshop and buy an "introduction to C programming" book. You'll end up knowing the language a lot better that way.
There is nothing more dangerous than a programmer who half understands C!
What you have to understand is that C doesn't actually have strings, it has character arrays. Moreover, the character arrays don't have associated length information -- instead, string length is determined by iterating over the characters until a null byte is encountered. This implies, that every char array should be at least strlen + 1 characters in length.
C doesn't perform array bounds checking. This means that the functions you call blindly trust you to have allocated enough space for your strings. When that isn't the case, you may end up writing beyond the bounds of the memory you allocated for your string. For a stack allocated char array, you'll overwrite the values of local variables. For heap-allocated char arrays, you may write beyond the memory area of your application. In either case, the best case is you'll error out immediately, and the worst case is that things appear to be working, but actually aren't.
As for the assignment, you can't write something like this:
char *str;
sprintf(str, ...);
and expect it to work -- str is an uninitialized pointer, so the value is "not defined", which in practice means "garbage". Pointers are memory addresses, so an attempt to write to an uninitialized pointer is an attempt to write to a random memory location. Not a good idea. Instead, what you want to do is something like:
char *str = malloc(sizeof(char) * (string length + 1));
which allocates n+1 characters worth of storage and stores the pointer to that storage in str. Of course, to be safe, you should check whether or not malloc returns null. And when you're done, you need to call free(str).
The reason your code works with the array syntax is because the array, being a local variable, is automatically allocated, so there's actually a free slice of memory there. That's (usually) not the case with an uninitialized pointer.
As for the question of how the size of a string can change, once you understand the bit about null bytes, it becomes obvious: all you need to do to change the size of a string is futz with the null byte. For example:
char str[] = "Foo bar";
str[1] = (char)0; // I'd use the character literal, but this editor won't let me
At this point, the length of the string as reported by strlen will be exactly 1. Or:
char str[] = "Foo bar";
str[7] = '!';
after which strlen will probably crash, because it will keep trying to read more bytes from beyond the array boundary. It might encounter a null byte and then stop (and of course, return the wrong string length), or it might crash.
I've written all of one C program, so expect this answer to be inaccurate and incomplete in a number of ways, which will undoubtedly be pointed out in the comments. ;-)
Your str3 is too short - you need to add extra byte for null-terminator and the length of "<-------------------->" string literal.
Out of curiosity, though, I tried
expanding the "concatenated" string to
be longer than the size I had
allocated. Much to my surprise, it
still worked and the string size
increased and could be printf'd fine.
The behaviour is undefined so it may or may not segfault.
strlen returns the length of the string without the trailing NULL byte (\0, 0x00) but when you create a variable to hold the combined strings you need to add that 1 character.
char str3[length3 + 1];
…and you should be all set.
C strings are '\0' terminated and require an extra byte for that, so at least you should do
char str3[length3 + 1]
will do the job.
In sprintf() ypu are writing beyond the space allocated for str3. This may cause any type of undefined behavior (If you are lucky then it will crash). In strlen(), it is just searching for a NULL character from the memory location you specified and it is finding one in 29th location. It can as well be 129 also i.e. it will behave very erratically.
A few important points:
Just because it works doesn't mean it's safe. Going past the end of a buffer is always unsafe, and even if it works on your computer, it may fail under a different OS, different compiler, or even a second run.
I suggest you think of a char array as a container and a string as an object that is stored inside the container. In this case, the container must be 1 character longer than the object it holds, since a "null character" is required to indicate the end of the object. The container is a fixed size, and the object can change size (by moving the null character).
The first null character in the array indicates the end of the string. The remainder of the array is unused.
You can store different things in a char array (such as a sequence of numbers). It just depends on how you use it. But string function such as printf() or strcat() assume that there is a null-terminated string to be found there.