iteration collect char in C - c

Here's my code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i,j,n;
scanf("%d",&n);
n*=n;
char str[n];
for(i=0;i<n;i++){
str[i]='*';
}
printf("%s",str);
printf("\n%d",strlen(str));
return 0;
}
I input 2 and this is the output I got:
2
****ú#
7
In line 2 it has some weird characters that show in console (U+0013 or control-S between ú and #), but it didn't show here.
Could you explain this to me?

printf("%s", str) assumes that str points to a NUL-terminated char array (aka "C string"). str is not NUL terminated in your case, so printf is running off the end of the buffer, resulting in undefined behavior.
To fix this you need to do two things:
Allocate an additional byte for the NUL terminator
NUL-terminate the array when you're finished writing to it
char str[n+1]
for(i=0;i<n;i++){
str[i]='*';
}
str[n] = '\0';

You are printing with %s format specifier which expects a C string(char array with NUL character at the end). You need to make the last character \0 to make printf recognize the end of the string and stop printing. So allocate one more character in the array and set the last character to \0.
char str[n+1];
str[n] = '\0`;

You need to NUL-terminate your string, like so:
char str[n+1]; /// <<<
for(i=0;i<n;i++){
str[i]='*';
}
str[n]='\0'; /// <<<

Related

C: String erroneously printing twice

I'm playing around with C strings as in the following programme:
#include <stdio.h>
int main(void){
char *player1 = "Harry";
char player2[] = "Rosie";
char player3[6] = "Ronald";
printf("%s %s %s\n", player1, player2, player3);
return 0;
}
Which prints the following:
Harry Rosie RonaldRosie
Why is "Rosie" printing out twice?
Ronald has 6 letters, so char player3[6] leaves no space for the null-terminator character '\0'.
In your case, it printed whatever comes after Ronald in memory until a '\0' was encountered. That happened to be Rosie. You might not always be so lucky and run into an error (e.g. memory protection) before finding a '\0'.
One solution (apart from how you initialized Harry and Rosie) is to increase the number of elements by one to provide space for a trailing '\0':
char player3[7] = "Ronald";

How to join two strings in C?

I have written this code but it's not working. It is showing some extra characters in the end. Here's the code:
// Program to concate/join two string
#include<stdio.h>
#include<string.h>
main()
{
int i,j,n=0;
char str[100],str2[100],str3[100];
printf("Enter string 1:\n");
gets(str);
printf("Enter string 2:\n");
gets(str2);
for(i=0;str[i]!='\0';i++)
{
str3[i]=str[i];
n=n+1;
}
for(i=0,j=n;str2[i]!='\0';i++,j++)
{
str3[j]=str2[i];
}
printf("The concanted sring is: \n");
puts(str3);
}
Terminate the str3 string with '\0' after you finish the copy loop:
for(i=0,j=n;str2[i]!='\0';i++,j++)
{
str3[j]=str2[i];
}
str3[j] = '\0'; // proper termination of the `str3`.
Otherwise the str3will continue till first random '\0' in the memory is encountered. That is why you get extra characters when you print str3.
Also read this: gets() function in C and
Why is the gets function so dangerous that it should not be used?
Avoid gets() in your programs!
In C language, a string is a null-terminated array of characters.
It is showing some extra characters in the end.
Reason for this is that you are not adding null character at the end of string str3 after concatenating str2 to it. Add a null-character at the end of the concatenated string, like this:
str3[j] = '\0';
Also, you should not use gets(). It has been obsoleted. Instead, use fgets().
Additional:
Follow the good programming practice, make a habit of specifying int as the return type of main function.
You can use one of best string manipulation function "strcat()" to concatenate to strings easily. try using below solution :
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "Hello" , str2[] = "There";
//concatenates str1 and str2 and resultant string is stored in str1.
strcat(str1,str2);
puts(str1);
puts(str2);
return 0;
}
Output:
HelloThere
There

Why does puts() function gives me a heart symbol?

I was trying to figure out that how a string with a known size can be filled with single characters. Then I wrote this simple code for a bigger problem that I have
(dynamic filling of a string with unknown size)
. When I tried to compile and run this code I encountered a problem which output had a heart symbol! and I don't know where it comes from.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
char str[3];
for(i=0;i<=2;i++){
str[i]=getc(stdin);
}
puts(str);
return 0;
}
Thank you.
The C strings are sequences of chars terminated by the null character (i.e. the character with code 0). It can be expressed as '\0', '\x0' or simply 0.
Your code fills str with three chars but fails to produce the null terminator. Accordingly, puts() prints whatever characters it finds in memory until it reaches the first null character.
Your code exposes Undefined Behaviour. It can do anything and it's not its fault.
In order to fix it you have to make sure the string ends with the null terminating character:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
// Make room for 3 useful chars and the null terminator
char str[4];
// Read three chars
for(i = 0; i < 3; i ++) {
str[i] = getc(stdin);
}
// Add the null terminator for strings
str[3] = 0;
puts(str);
return 0;
}
Update
As #JeremyP notes in a comment, if the file you read from (stdin) ends before the code reads 3 characters, fgetc() will return EOF (End Of File) characters that are also funny non-printable characters that makes you wonder where they came from.
The correct way to write this code is to check if the input file reached its EOF (feof()) before reading from it:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
// Make room for 3 useful chars and the null terminator
char str[4];
// Read at most three chars
for(i = 0; i < 3 && !feof(stdin); i ++) {
str[i] = getc(stdin);
}
// Add the null terminator for strings
str[i] = 0;
puts(str);
return 0;
}
Strings in c need to be null terminated so it could be that you forgot to add a '\0' character to the end of str. The reason the heart symbol shows up would be that when puts() tries to write out a string it keeps reading the next character in memory until it reaches a null terminator, '\0'. Since it doesn't encounter one it just continues reading into memory and happens to find the heart symbol I'd guess. Hope this helps.

why string a gets appended to string b in this code

i am writing a basic c program to display two strings, one taken from user i.e "a" and the other being defined in code "b" but when i run the code below string "a" gets appended to "b". why? and what is that symbol at end of "a"
updated code:
#include <stdio.h>
#include <string.h>
int main()
{
char a[ 5 ];
int i=0;
while(i<5)
{
a[i]=getchar();
i++;
}
char b[]={'r','f','s','/0'};
printf("output:-");
printf("\n %s",a);
printf("\n %s",b);
return 0;
console
qwert
output:-qwert$
rfs$qwert$
there is a some special symbol instead of $ above, what is it?
Putting all the comments into an answer. The problems in the original code stem mostly from not NUL terminating the character arrays to produce valid C strings.
a is not NUL terminated. Can fix by increasing the a array by 1 and explicitly writing a NUL to the last byte.
b is not NUL terminated. Can fix by initialising b using a literal string or a char array with '\0' as the last byte. The example below uses the former.
Here is the full code with the errors corrected. Note that the code to read input is fragile as it only accepts exactly a 5 character string.
#include <stdio.h>
#include <string.h>
int main(void)
{
char a[6];
int i=0;
while (i<5) {
a[i]=getchar();
i++;
}
a[i] = '\0';
char b[]="rfs";
printf("output:-\n");
printf(" %s\n",a);
printf(" %s\n",b);
return 0;
}

Need help finding bug, if string input is composed all of same character one output character is corrupt

reverser() reverses a cstring (not in place). 99% of the time it works but some input corrupts it for example it appears if aStr2[] is assigned a string made up of the same character it will have an error.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* reverser(const char *str);
int main()
{
char aStr[] = "aaa";
char aStr2[] = "cccccc";
printf("%s %s", aStr, aStr2);
char* tmp = reverser(aStr2);//tmp now has garbage
printf("\n%s", tmp);
printf(" %s", aStr2);
return 0;
}
char* reverser(const char *str)
{
char* revStr = (char*)malloc(strlen(str));
int i;
for(i = strlen(str)-1; i >= 0; i--)
{
revStr[strlen(str)-1-i] = str[i];
}
return revStr;
}
Gives
aaa cccccc
cccccc9 cccccc
Process returned 0 (0x0) execution time : 0.068 s
Press any key to continue
Notice the 9 that shouldn't be there.
Change this malloc to strlen(str) + 1 , plus 1 for '\0'
char* revStr = (char*)malloc(strlen(str) + 1);
and after the for loop
revStr[strlen(str)+1] = '\0';
Your problem is that you don't put the string terminator in your reversed string. All strings in C are actually one extra character that isn't reported by strlen, and that is the character '\0' (or plain and simple, a zero). This tells all C functions when the string ends.
Therefore you need to allocate space for this extra terminator character in your malloc call, and add it after the last character in the string.
There are also a couple of other problems with your code, the first is that you should not cast the return of malloc (or any other function returning void *). Another that you have a memory leak in that you do not free the memory you allocate. This last point doesn't matter in a small program like the one you have here, but will be an issue in larger and longer running programs.
You haven't null-terminated your reversed string. You need to set the final index of revStr[] to 0.

Resources