C programming, segmentation fault core dump - c

I am trying to make a program which takes in a input of "Hello" and outputs "olleH" from reversing the order of the characters. However I keep getting a segmentation fault and I don't understand why
#include <stdio.h>
#include<string.h>
int main()
{
int i;
int size;
char s[100],a[100];
printf("Enter the word you want to get reversed: ");
scanf("%s",s);
while(s[i]!='\0')
{
a[i]=s[i];
i++;
}
size=sizeof(s);
while(i<sizeof(s))
{
s[i]=a[size];
}
printf("The reversed string is : %s",s);
}

Another simple way to reverse string.
Try this:
while(s[++i]!='\0'); // find the size of string
while(i>=0)
a[j++] = s[--i]; // reverse the string
a[j]='\0';
printf("The reversed string is : %s",a);

This while loop
while(i<sizeof(s))
{
s[i]=a[size];
}
does not make sense because index i has a value that points to outside the entered string (provided that it was initially correctly initialized) and the loop is infinite because i is not changed (and was not initially initialized) in the loop and also the right hand expression of this statement
s[i]=a[size];
is always the same and again refers memory outside the array.
Take into account that neither function declared in <string.h> is used in the program. So the header may be removed.
The program can look the following way
#include <stdio.h>
#define N 100
int main()
{
char s[N], d[N];
printf( "Enter the word you want to get reversed: " );
fgets( s, N, stdin );
size_t n = 0;
while ( s[n] != '\0' && s[n] != '\n' ) n++;
for ( size_t i = 0; i != n; i++ ) d[i] = s[n-i-1];
d[n] = '\0';
printf( "The reversed string is : %s\n", d );
return 0;
}
You can reverse a string without using an auxiliary array. For example
#include <stdio.h>
#define N 100
int main()
{
char s[N];
printf( "Enter the word you want to get reversed: " );
fgets( s, N, stdin );
size_t n = 0;
while ( s[n] != '\0' && s[n] != '\n' ) n++;
s[n] = '\0';
for ( size_t i = 0; i < n / 2; i++ )
{
char c = s[i];
s[i] = s[n-i-1];
s[n-i-1] = c;
}
printf( "The reversed string is : %s\n", s );
return 0;
}

The problem is in this part:
size=sizeof(s);
while(i<sizeof(s))
{
s[i]=a[size];
}
sizeof(s) will be 100 whereas the string you read from input can be less than that -- which would be undefined if you access uninitialized parts of s. So, you want to use strlen() to get the actual size of the string and use it to reverse.
Notice that scanf() is unsafe as it's written (what if you input more than 100 chars?). Suggest using fgets() instead.

Related

How to give out a word backwards in c

Can someone help me with my code. I have to create a program, where the user puts in a word and that word has to be given out backwards.
My code doesn't really work, because the backward word puts out some random characters and then gives out the right word.
#include <stdio.h>
int main(){
char word[10];
printf("Please enter a word : ");
scanf("%s", word);
for (int i = 10; i >= 0; i--){
if (word[i] !=0){
printf("%c", word[i]);
}
}
return 0;
}
For starters this call of scanf
scanf("%s", word);
is unsafe. You need at least to specify the length of the entered string like
scanf("%9s", word);
The second problem is that the user can enter less than 9 characters. So this for loop
for (int i = 10; i >= 0; i--){
is incorrect. And moreover the index equal to 10 points to memory outside the array. So this if statement
if (word[i] !=0){
in any case wrong when i is equal to 10.
You need to find the length of the entered string.
The program can look the following way
#include <stdio.h>
#include <string.h>
int main( void )
{
char word[10];
printf( "Please enter a word : " );
if ( scanf( "%9s", word ) == 1 )
{
for ( size_t n = strlen( word ); n != 0; --n )
{
putchar( word[n-1] );
}
putchar( '\n' );
}
}
You're accessing outside the array, since your loop starts at i=10, but the last element of the array is word[9]. And if the user types less than 9 characters, you'll print uninitialized characters.
Use strlen() to determine how long the word is. Then subtract 1 from this to get the index of the last character.
for (int i = strlen(word)-1; i >= 0; i--)
You should also print a newline at the end.

Counting Characters and Strings n C

This is one of the assignments for my class and this is the objective of the assignment:
Write a program whose input is a character and a string, and whose output indicates the number of times the character appears in the string. The output should include the input character and use the plural form, n's, if the number of times the characters appears is not exactly 1. You may assume that the string does not contain spaces and will always contain less than 50 characters.
This is the code I have so far and I am new to C programming so I don't know how to declare Strings correctly just yet. So far I learned there are no strings in C like there is in Java and you have to do them as a character array:
#include <stdio.h>
#include <string.h>
int main(void) {
char userChar;
char userString[50];
int count = 0;
for (int i = 0; i < userChar; i++) {
if (userString[i] == userChar)
count++;
}
printf("%d", count);
if (count != 1)
printf("'s");
return 0;
}
For example, if I wanted to input n Monday and output 1 n
What would I need to change in my code to go from n Monday to 1 n
This is the only output I am getting, and it only has outputted one thing correctly:
0's
First, I hope this is not considered cheating :-)
Second, you need to define userChar and userString as arguments for main, and pass them in at run time. They are assigned nothing, so that is why you get
0's
Third, your for condition is wrong. You need this so it only iterates through the length of the string:
for (int i = 0; i < strlen(userString); i++)
Finally, You are not printing the value of userChar prior to the return
At first you need to input a string and a character. To count the number of occurrences of the character in the string you can use standard string function strchr.
The program can look something like the following
#include <stdio.h>
#include <string.h>
int main(void)
{
char userChar = ' ';
char userString[50] = "";
printf( "Enter a string without embedded spaces\nof the length less than %d: ", 50 );
scanf( "%49s", userString );
printf( "Enter a character to search in the string: " );
scanf( " %c", &userChar );
size_t n = 0;
for ( const char *p = userString; ( p = strchr( p, userChar ) ) != NULL; ++p )
{
++n;
}
printf( "%zu%s %c\n", n, n < 2 ? "" : "'s", userChar );
}
The expected output is not 0's, it should include the counted character: for example if the character is n and the string Monday, the output should be
1 n
and if the string is Eeny-meeny-miny-moe, the output would be
3 n's
Here is a modified version:
#include <stdio.h>
int main() {
char userChar;
char userString[50];
int i, count;
printf("Enter character: ");
scanf(" %c", &userChar);
printf("Enter string (single word): ");
// read a word with at most 49 characters
scanf(" %49s", userString);
count = 0;
for (i = 0; userString[i] != '\0'; i++) {
if (userString[i] == userChar)
count++;
}
printf("%d %c", count, userChar);
if (count != 1)
printf("'s");
printf("\n");
return 0;
}

pallindrome program not working please check attached the code and the output

i have tried to make a program to check the pallindrome manually on paper it should work
but it doesnt.
i have attached the output with the code
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <stdlib.h>
void main()
{
char str[100];
int i,l,k;
printf("type the desired to string to check pallindrome\n");
gets(str);
l=strlen(str);
printf("%d\n", l);
k=l-1;
char temp[100];
for(i=0;i<l;i++)
{
temp[k]=str[i];
--k;
}
if(strcmp(temp, str)==0)
{
printf("pallindrome\n");
}
else
{
printf("not a pallindrome\n");
}
}
here is the output
[1]: https://i.stack.imgur.com/dERFQ.png
You need to append the NUL terminator at the end of temp right after the for loop:
for(i=0;i<l;i++)
{
temp[k]=str[i];
--k;
}
temp[i] = '\0';
Otherwise, the strcmp function will cause UB.
For starters according to the C Standard the function main without parameters shall be declared like
int main( void )
The array temp does not contain a string because you forgot to append it with the terminating zero character '\0'.
So the call of the strcmp
if(strcmp(temp, str)==0)
results in undefined behavior.
Also the function gets is unsafe and is not supported by the C Standard. Instead use the function fgets.
Also to check whether a string is a palindrome there is no need to declare an auxiliary array.
The code can look like
printf("type the desired to string to check pallindrome\n");
fgets(str, sizeof( str ), stdin );
str[strcspn( str, "\n" )] = '\0'; // to remove the new line character '\n'
size_t n = strlen( str );
printf( "%zu\n", n );
size_t i = 0;
while ( i < n / 2 && str[i] == str[n-i-1] ) ++i;
if( i == n / 2 )
{
printf("pallindrome\n");
}
else
{
printf("not a pallindrome\n");
}
You could write a separate function that checks whether a string is a palindrome.
Here you are.
#include <stdio.h>
#include <string.h>
int is_palindrome( const char *s )
{
size_t n = strlen( s );
size_t i = 0;
while ( i < n / 2 && s[i] == s[n-i-1] ) ++i;
return i == n / 2;
}
int main(void)
{
enum { N = 100 };
char s[N];
printf( "Type a desired string to check whether it is a palindrome: " );
fgets( s, sizeof( s ), stdin );
s[ strcspn( s, "\n" ) ] = '\0';
if ( is_palindrome( s ) )
{
printf( "\"%s\" is a palindrome.\n", s );
}
else
{
printf( "\"%s\" is not a palindrome.\n", s );
}
return 0;
}
The program output might look like
Type a desired string to check whether it is a palindrome: abcdedcba
"abcdedcba" is a palindrome

Why puts() prints some garbage values on output in C

I'm trying to do a function in C language that it's checking if a String is palindromic (read the same way from the begging to the end and backwards ) . So I use the puts() function to print the String backwards and after a number of elements (>7) it prints some unwanted characters.
My routine is :
void isPal ( char ptr[], int i){
char array[i];
int j=0,k=0;
int l = i-1;
for (j=0; j<i ; j++){
array[j] = ptr[l]; printf("%c\t", array[j] );
printf("Character :%c -> [%d]\n", array[j],l );
l--;
}
printf("\nThe upside string is : ");
puts(array);
for (k=0; k<i ; k++){
if ( array[k] != ptr[k]){
printf("\nNot palindromic!!!\n");
return;
}
}
printf("\nIS PALINDROMIC..\n");
}
The result is accurate but the printing isn't right . Why that ?
The created array does not contain a string because there is no the terminating zero in the array.
Also there is no need to define an auxiliary array to determine whether the passed string is a palindrome.
Creating a variable length array within the function is unsafe and can result in a stack overflow. Apart from this the user of the function can pass to the function the second argument less than or equal to 0. In this case the function will have undefined behavior.
The function should do only one thing i.e. to determine whether the passed string is a palindrome.
It is the caller of the function that will decide what message to output if any.
The function parameter that specifies the array should have the qualifier const because the passed string is not being changed in the function.
The function can be defined the following way
int isPal ( const char *s )
{
size_t n = strlen( s );
size_t i = 0;
while ( i < n / 2 && s[i] == s[n-i-1] ) ++i;
return i == n / 2;
}
Here is a demonstrative program.
#include <stdio.h>
#include <string.h>
int isPal ( const char *s )
{
size_t n = strlen( s );
size_t i = 0;
while ( i < n / 2 && s[i] == s[n-i-1] ) ++i;
return i == n / 2;
}
int main(void)
{
const char *s = "123454321";
printf( "The string \"%s\" is %sa palindrome.\n",
s, isPal( s ) ? "" : "not " );
return 0;
}
Its output is
The string "123454321" is a palindrome.
Just replace char array[i]; with following two lines:
char array[i+1];
array[i] = '\0';
puts() takes string as an argument. In c, string is basically a character array with '\0' at the end. So, when we add '\0' at the end of array[] it becomes a string and as a result puts() does not show any unpredictable behaviour.

Reversing String Only Using For Loop

I have been trying to reverse(and print it that way) a given string only using for loops and nothing more. I think I have built up the basic logic, but it has some defects. When run, it only reverses the first two characters and then stops. Please help me find the defect in my logic.
#include<stdio.h>
#include<stdlib.h>
int main()
{
char a[20];
int i;
printf("Enter any String\n");
gets(a);
for(i=0;a[i]!=NULL;i++)
{}
for(i=1;i>=0;i--)
{
printf("%c",a[i]);
}
}
For starters the function gets is not a standard C function any more. it is unsafe. Instead use the standard C function fgets. The function can append the new line character '\n' to the entered string that should be excluded from the string.
It is unclear from your question whether you are allowed to use standard string functions.
Nevertheless here is a demonstrative program that does the task without using standard C string functions and that uses only for loops (neither while loop nor do-while loop).
#include <stdio.h>
int main(void)
{
enum { N = 20 };
char s[N];
printf( "Enter any String less than %d symbols: ", N );
fgets( s, N, stdin );
// remove the new line character and calculate the length of the string
size_t n = 0;
for ( ; s[n] != '\0' && s[n] != '\n'; ) ++n;
s[n] = '\0';
// reverse the string
for ( size_t i = 0; i < n / 2; i++ )
{
char c = s[i];
s[i] = s[n-i-1];
s[n-i-1] = c;
}
puts( s );
return 0;
}
Its output might look the following way
Enter any String less than 20 symbols: Hello dev.aniruddha
ahddurina.ved olleH
If you want just to output the original string in the reverse order then the program can look like
#include <stdio.h>
int main(void)
{
enum { N = 20 };
char s[N];
printf( "Enter any String less than %d symbols: ", N );
fgets( s, N, stdin );
// remove the new line character and calculate the length of the string
size_t n = 0;
for ( ; s[n] != '\0' && s[n] != '\n'; ) ++n;
s[n] = '\0';
// reverse the string
for ( ; n-- != 0; )
{
putchar( s[n] );
}
putchar( '\n' );
return 0;
}
Its output is the same as shown above
Enter any String less than 20 symbols: Hello dev.aniruddha
ahddurina.ved olleH
gets() is a bad idea as you can easily get overflows and it is no longer part of the c standard.
So let's assume that the string entered fits the array and this is just for an excercise with no reallife usage.
Your first loop finds the terminator. That's good.
Your second loop sets the variable that indicates the terminator to 1, destroying the result.
If you remove the assignment i=1, your program compiles with gcc and does what you want.
#include<stdio.h>
#include<stdlib.h>
int main()
{
char a[20];
int i;
printf("Enter any String\n");
gets(a);
for(i=0;a[i]!=NULL;i++)
{}
for(;i>=0;i--) //removed i=1 here
{
printf("%c",a[i]);
}
}
But there are still some issues to be addressed.
You will also reverse the terminator, instead you should start from i-1
I would advise to not use a for loop if you do not have a counter criterion The first loop should rather be a while loop, but as it was part of the assignment you had no choice still I will replace it in my recommendation. As they can easily be swapped.
Then you could use another variable for the second loop for clarity.
Also NULL is the NULL-pointer not the value 0 (also namend NUL apperantly) . So you should replace this either with 0 or with '\0'
Also stdlib.h is not required here
#include<stdio.h>
int main()
{
char a[20];
int i = 0;
printf("Enter any String\n");
gets(a);
while (a[i] != 0)
{
i++;
}
for(int j = i-1; j>=0; j--) // -1 to get the value in front of the terminator
{
printf("%c",a[j]);
}
printf("\n"); //to flush the output.
}
Here is the solution code.
The first for loop is to be used for determining the length of the string and the second for loop is for traversing the string from the last position to the first.
#include<stdio.h>
int main()
{
char a[20];
int i,j,len;
printf("Enter a String\n");
gets(a);
for(i=0;a[i]!=NULL;i++)
{}
len=i;
for(j=len-1;j>=0;j--)
{
printf("%c",a[j]);
}
}
I think why only two chars are been return is because of the condition statement in your second "for loop".
for(i=1;i>=0;i--)
Note:
it repeats from 1~0 (1,0): meaning it will repeat only twice
first iteration: when i == 1
second iteration: when i == 0 ; then it ends .
Please note that you created two "for loops" with the first one having no content.
Bonus:
I tried to fixed your code but realized that my C language skills isnt the best lol . Anyways, i came up with something that you could reference but it only reverse strings of less than 8 elements.
#include<stdio.h>
#include<stdlib.h>
int findlength(char a[]);
int main()
{
char a[20];
int i;
printf("Enter any String\n");
gets(a);
int len = findlength(a);
printf("Lenght of the String is: %d \n",len);
printf("Reversed String is: ");
for(i=len;i>-1;i--){
printf("%c",a[i]);
}
}
int findlength(char a[]){
int result = 0;
int i;
for(i=0;i<sizeof(a) / sizeof(char);i++){ // sizeof(char) is 1
if(a[i] == '\0') //end of string
return result;
result += 1;
}
return result;
}

Resources