I would like to concatenate 2 strings in C using strcat(), but it is always add some random characters to the beginning of the new concatenated string.
Could someone please tell me why is this happening and how to solve it?
This is my code:
#include "stdio.h"
#include "string.h"
int main(void)
{
char text[100];
strcat(text, "Line 1");
strcat(text, "Line 2");
printf("%s", text);
return 0;
}
When I execute this I get the following output:
??? Line1Line2
I would appreciate any help.
Thank you.
The line
strcat(text, "Line 1");
has undefined behavior, because both arguments of the strcat function call must point to strings, i.e. to null-terminated sequences of characters. However, the first argument is not guaranteed to point to a string, because text consists of indeterminate values, because it is not initialized.
You have two options to fix this bug. You can either
before the first call to strcat, set the first character of text to a terminating null character, i.e. text[0] = '\0';, so that text contains a valid (empty) string, or
replace the first function call to strcat with strcpy, because strcpy does not require that the first function argument points to a valid string.
Related
Why does the second strncpy give incorrect weird symbols when printing?
Do I need something like fflush(stdin) ?
Note that I used scanf("%s",aString); to read an entire string, the input that is entered starts first off with a space so that it works correctly.
void stringMagic(char str[], int index1, int index2)
{
char part1[40],part2[40];
strncpy(part1,&str[0],index1);
part1[sizeof(part1)-1] = '\0';//strncpy doesn't always put '\0' where it should
printf("\n%s\n",part1);
strncpy(part2,&str[index1+1],(index2-index1));
part2[sizeof(part2)-1] = '\0';
printf("\n%s\n",part2);
}
EDIT
The problem seems to lie in
scanf("%s",aString);
because when I use printf("\n%s",aString); and I have entered something like "Enough with the hello world" I only get as output "Enough" because of the '\0'.
How can I correctly input the entire sentence with whitespace stored? Reading characters?
Now I use: fgets (aString, 100, stdin);
(Reading string from input with space character?)
In order to print a char sequence correctly using %s it needs to be null-terminated. In addition the terminating symbol should be immediately after the last symbol to be printed. However this section in your code: part2[sizeof(part2)-1] = '\0'; always sets the 39th cell of part2 to be the 0 character. Note that sizeof(part2) will always return the memory size allocated for part2 which in this case is 40. The value of this function does not depend on the contents of part2.
What you should do instead is to set the (index2-index1) character in part2 to 0. You know you've copied that many characters to part2, so you know what is the expected length of the resulting string.
I'm learning C and am currently experimenting with storing strings in variables. I put together the following to try different stuff.
#include <stdio.h>
int main() {
char *name = "Tristan";
char today[] = "January 1st, 2016";
char newyear[] = {'H','a','p','p','y',' ','N','e','w',' ','Y','e','a','r','!','\n'};
printf("Hello world!\n");
printf("My name is %s.\n", name);
printf("Today is: %s.\n", today);
printf(newyear);
return 0;
}
After compiling this code and running it, I get the following results:
Hello world!
My name is Tristan.
Today is: January 1st, 2016.
Happy New Year!
January 1st, 2016
Now this is pretty much what I would expect, by why would "January 1st, 2016" get printed out again at the end of the program's output?
If I take the "\n" out of the "newyear" array, it will not do this.
Would someone please explain why this is?
newyear misses a trailing null byte, so printfing it is undefined behavior.
Only string literals implicitly append a null byte. You explicitly initialize every character, so no null byte is appended.
Undefined behavior means that something the standard does not define in this occasion will happen. That includes nothing happening, you bursting into tears, or, yes, printing some string twice.
Just add an additional character, i.e., a null byte to the array to resolve the problem:
char newyear[] = {'H','a','p','p','y',' ','N','e','w',' ','Y','e','a','r','!','\n', '\0'};
Note that no sane person initializes an automatic char array with a string like that. Just stick to string literals! (I think you did it just for learning purposes, though.)
Remember that strings in C are terminated by the special '\0' character.
Not having this terminator at the end of data that is treated as a string will lead to undefined behavior as the string functions pass the end of the data searching for the terminator.
This because you are defining newyear directly as a char array and not through the string literal "" syntax. This prevents the compiler from adding a trailing \0 character which is required to mark the end of a string.
Since both newyear and today reside on stack, in this case they have contiguous storage there so printf keeps after the \n of newyear and prints contents of memory until a \0 is found.
newyear should finish with a '\0' instead of the newline, to be a C string. You can then put the newline in the printf statement, like the others:
char newyear[] = {'H','a','p','p','y',' ','N','e','w',' ','Y','e','a','r','!','\0'};
//...
printf("%s.\n", newyear);
Or, you can add the string terminator to the array, and use the printf as you did:
char newyear[] = {'H','a','p','p','y',' ','N','e','w',' ','Y','e','a','r','!','\n','\0'};
//...
printf(newyear);
In your first two examples, a string defined as "my string" automatically has the '\0' appended, by the compiler.
So I'm writing a small program (I'm new to C, coming from C++), and I want to take in a string of maximum length ten.
I declare a character array as
#define SYMBOL_MAX_LEN 10 //Maximum length a symbol can be from the user (NOT including null character)
.
.
.
char symbol[SYMBOL_MAX_LEN + 1]; //Holds the symbol given by the user (+1 for null character)
So why is it when I use:
scanf("%s", symbol); //Take in a symbol given by the user as a string
I am able to type '01234567890', and the program will still store the entire value?
My questions are:
Does scanf not prevent values from being recorded in the adjacent
blocks of memory after symbol?
How could I prevent the user from entering a value of greater than length SYMBOL_MAX_LEN?
Does scanf put the null terminating character into symbol automatically, or is that something I will need to do manually?
You can limit the number of characters scanf() will read as so:
#include <stdio.h>
int main(void) {
char buffer[4];
scanf("%3s", buffer);
printf("%s\n", buffer);
return 0;
}
Sample output:
paul#local:~/src/c/scratch$ ./scanftest
abc
abc
paul#local:~/src/c/scratch$ ./scanftest
abcdefghijlkmnop
abc
paul#local:~/src/c/scratch$
scanf() will add the terminating '\0' for you.
If you don't want to hardcode the length in your format string, you can just construct it dynamically, e.g.:
#include <stdio.h>
#define SYMBOL_MAX_LEN 4
int main(void) {
char buffer[SYMBOL_MAX_LEN];
char fstring[100];
sprintf(fstring, "%%%ds", SYMBOL_MAX_LEN - 1);
scanf(fstring, buffer);
printf("%s\n", buffer);
return 0;
}
For the avoidance of doubt, scanf() is generally a terrible function for dealing with input. fgets() is much better for this type of thing.
Does scanf not prevent values from being recorded in the adjacent blocks of memory after symbol?
As far as I know, No.
How could I prevent the user from entering a value of greater than length SYMBOL_MAX_LEN?
By using buffer safe functions like fgets.
Does scanf put the null terminating character into symbol automatically, or is that something I will need to do manually?
Only if the size was enough for it to put the nul terminator. For example if your array was of length 10 and you input 10 chars how will it put the nul terminator.
I am able to type '01234567890', and the program will still store the entire value?
This is because you are Unlucky that you are getting your desired result. This will invoke undefined behavior.
Does scanf not prevent values from being recorded in the adjacent blocks of memory after symbol?
No.
How could I prevent the user from entering a value of greater than length SYMBOL_MAX_LEN?
Use fgets.
Does scanf put the null terminating character into symbol automatically, or is that something I will need to do manually?
Yes
I need to define the characters in an array and print the string...But it always prints as string7 (in this case, test7)...What am I doing wrong here?
#include <stdio.h>
int main() {
char a[]={'t','e','s','t'};
printf("%s\n",a);
return 0;
}
Why this behavior?
Because you did not \0 terminate your array, so what you get is Undefined behavior.
What possibly happens behind the scenes ?
The printf tries to print the string till it encounters a \0 and in your case the string was never \0 terminated so it prints randomly till it encounters a \0.
Note that reading beyond the bounds of allocated memory is Undefined behavior so technically this is a UB.
What you need to do to solve the problem?
You need:
char a[]={'t','e','s','t',`\0`};
or
char a[]="test";
Because your "string", or char[], is not null-terminated (i.e. terminated by \0).
then, printf("%s", a); will attempt to print every character starting from the start of a and keep printing until it sees until it sees a \0.
That \0 is outside your array, and depends on the initial state of the memory of your program, which you pretty much don't have control.
to fix this, use
char a[]={'t','e','s','t','\0'};
The string you printing must be null terminated...so your string declaration should be,
char a[]={'t','e','s','t', '\0'};
I'm running into an odd problem with concatenating or printing strings. I have a char * that can be set to one of a few values of string literal.
char *myStrLiteral = NULL;
...
if(blah)
myStrLiteral = "foo";
else if(blahblah)
myStrLiteral = "bar";
And I have some other strings that I get from library functions or that are concatenations of input - they're either malloc'ed or stack variables. When I try to print (or concatenate using strcpy() and strcat(), the result is the same), even though I print the string literal last, it prints over the initial characters of the entire string I'm constructing or printing.
/* otherString1 contains "hello", otherString2 contains "world" */
printf("%s %s %s\n", otherString1, otherString2, myStrLiteral);
/* prints "barlo world" */
Am I misunderstanding something about string literals in C?
Check that the literals you're receiving contain only the bytes you expect:
void PrintBytes(const char *s)
{
while (*s) {printf("%d ", *s); s++;}
}
PrintBytes(otherString1);
PrintBytes(otherString2);
PrintBytes(myStrLiteral);
My suspicion is that one of them contains an embedded control character.
If you don't care about finding out which control character is involved, you could simply print the length of each string. If it's longer than it ought to be, there's a control character in there somewhere:
printf("%d\n%s\n", strlen(otherString1), otherString1);
The only thing I can think of is that the otherString2 contains a carriage return, but not a line feed.
to find out
You can strlen otherString2 and see if it matches what you see
You can look at otherString2 with a debugger and see if 0x0D is before the 0x00 terminating the string.