C language Segmentation fault (core dumped) while coding strings - c

First i'm gonna apologize for my english as it's kinda meh and also it's my first time asking programming questions online so sorry if I make it unclear
So, my problem is that I need a code that puts space before every capital letter in a string
Example: AaaBbbCcC= Aaa Bbb Cc C
However, I encountered the error
Error
Segmentation fault (core dumped)
while doing so.
//this function takes a string from int main at the end of the code
void function(char s[]){
int stringsize=0;
int a;
while(s[stringsize]!='\0'){
stringsize++;
}
//I made this while to find the size of the string given
stringsize++;
a=stringsize;
//I used 'a' to have two variables to store this data
//here I made a for to do the hard work and add a space before every capital letter, it simply sends everyone one house ahead and then put a space where it found the capital letter
for(int i=0; s[i]!='\0'; i++){
if(s[i]>='A'&&s[i]<='Z'){
while(a>i){
a--;
s[a+1]=s[a];
}
s[a]=' ';
//the code works perfectly until here, it do its purpose, but since the while reduces the value of 'a' to the first capital letter it only works once, so here is the reason why I made two variables at the beginning, it adds 1 to stringsize (since the string grew one house) and gives the variable 'a' the new value to keep the for going. However, when I add this two lines of code the error Segmentation fault (core dumped) appears
stringsize++;
a=stringsize;
}
}
}
int main()
{
char s[TAM];
//TAM is equal to 500 btw, I made a define just didn't put it here
scanf("%199[^\n]s", s);
function(s);
printf("%s", s);
return 0;
}
Hope I made it clear enough, as I said i'm not a native english speaker and I'm a beginner at programing

The problem is that when it inserts a space, it does not skip past the capital letter it just found, but instead keeps moving it and inserting spaces indefinitely. You can fix it by incrementing i after inserting a space:
#include <stdio.h>
#define TAM 500
void function(char s[])
{
int stringsize=0;
int a;
while (s[stringsize] != '\0') {
stringsize++;
}
stringsize++;
a=stringsize;
for (int i=0; s[i]!='\0'; i++) {
if (s[i] >= 'A' && s[i] <= 'Z') {
while (a > i) {
a--;
s[a+1] = s[a];
}
s[a]=' ';
stringsize++;
a=stringsize;
i++; // add this line
}
}
}
int main(void)
{
char s[TAM];
scanf("%199[^\n]s", s);
function(s);
printf("%s\n", s);
return 0;
}

Related

Runtime error in codeforces but worked just fine in Dev-C++

I'm trying to solve a problem which requires: a sentence that has less than 150 characters as an input and makes that sentence's characters all to uppercase while removing all extra white spaces, then prints the changed sentence and its number of characters to the screen.
For example: Input: Look in to the abyss Output:LOOK IN TO THE ABYSS:20
I tested this program on Dev-C++ and it worked just fine but when i submitted it to CodeForces I got runtime error. I hope anyone can help me with this.
( I tried to use scanf("%[^\n]%*c", sen) and fgets(sen, sizeof(sen), stdin) instead of gets(sen) but i still get runtime error. Also, i use a different function strlength instead of strlen since i had another type-related error when submitting that piece of code to CodeForces ) P/s: Sorry for my bad English
#include <ctype.h>
#include <stdio.h>
int strlength(char* str){
int i,j = 0;
for (i=0; str[i]!= '\0';i++)
++j;
return j;
}
void strip_white_spaces(char* str){
int x,i;
for (x=i=0; str[i]!='\0';i++){
if (!isspace(str[i])||((i>0) && (!isspace(str[i-1]))))
str[x++] = str[i];
}
if (isspace(str[x-1]))
str[x-1]='\0';
else str[x] ='\0';
}
void touppercase(char* str){
int i;
for (i = 0; str[i] != '\0';i++ ){
if (str[i] >= 'a' && str[i] <= 'z')
str[i] -= 32;
}
}
void main(){
char sen[150];
gets(sen);
strip_white_spaces(sen);
touppercase(sen);
int s = strlength(sen);
printf("%s:%d", sen, s);
}
isspace(str[i-1]) will read out of bounds for i == 0, which might cause the program to crash if you are lucky. You need to rewrite that function with different logic.
I found the bug !
The error turned out to be at 'void main()' function.
When i replaced it with int main(), i got perfect results in CodeForces.
Thanks everyone for helping me !

Program to get an indefinite number of strings in C and print them out

As part of an assignment, I am supposed to write a small program that accepts an indefinite number of strings, and then print them out.
This program compiles (with the following warning
desafio1.c:24:16: warning: format not a string literal and no format arguments [-Wform
at-security]
printf(words[i]);
and it prints the following characters on the screen: �����8 ���#Rl�. I guess it did not end the strings I entered by using getchar properly with the null byte, and it prints out garbage. The logic of the program is to initiate a while loop, which runs untill I press the enter key \n, and if there are an space, this is a word that will be store in the array of characters words. Why am I running into problems, if in the else statement once a space is found, I close the word[i] = \0, in that way and store the result in the array words?
#include <stdio.h>
#include <string.h>
int main()
{
char words[100][100];
int i,c;
char word[1000];
while((c = getchar()) != '\n')
{
if (c != ' '){
word[i++] = c;
c = getchar();
}
else{
word[i] = '\0';
words[i] == word;
}
}
int num = sizeof(words) / sizeof(words[0]);
for (i = 0; i < num; i++){
printf(words[i]);
}
return 0;
}
Here are some fixes to your code. As a pointer (as mentioned in other comments), make sure to enable compiler warnings, which will help you find 90% of the issues you had. (gcc -Wall)
#include <stdio.h>
#include <string.h>
int main() {
char words[100][100];
int i = 0;
int j = 0;
int c;
char word[1000];
while((c = getchar()) != '\n') {
if (c != ' '){
word[i++] = c;
} else {
word[i] = '\0';
strcpy(words[j++], word);
i = 0;
}
}
word[i] = '\0';
strcpy(words[j++], word);
for (i = 0; i < j; i++) {
printf("%s\n", words[i]);
}
return 0;
}
i was uninitialized, so its value was undefined. It should start at 0. It also needs to be reset to 0 after each word so it starts at the beginning.
The second c = getchar() was unnecessary, as this is done in every iteration of the loop. This was causing your code to skip every other letter.
You need two counters, one for the place in the word, and one for the number of words read in. That's what j is.
== is for comparison, not assignment. Either way, strcpy() was needed here since you are filling out an array.
Rather than looping through all 100 elements of the array, just loop through the words that have actually been filled (up to j).
The last word input was ignored by your code, since it ends with a \n, not a . That's what the lines after the while are for.
When using printf(), the arguments should always be a format string ("%s"), followed by the arguments.
Of course, there are other things as well that I didn't fix (such as the disagreement between the 1000-character word and the 100-character words). If I were you, I'd think about what to do if the user entered, for some reason, more than 1000 characters in a word, or more than 100 words. Your logic will need to be modified in these cases to prevent illegal memory accesses (outside the bounds of the arrays).
As a reminder, this program does not accept an indefinite number of words, but only up to 100. You may need to rethink your solution as a result.

program to remove special characters and number from string and only print english letter

this is what i tried.
this works properly for small string like wel$co*me
but gives weird output for pass#word. where am i going wrong exactly?
#include <stdio.h>
#include <string.h>
int main()
{
char s[100],rs[100];
int i,c=0;
scanf("%s",s);
int n = strlen(s);
for(i=0;i<n;i++)
{
if(((int)s[i] >= 65 && (int)s[i] <= 90) ||((int)s[i] >=97 && (int)s[i] <= 122) )
{
rs[c] = s[i];
c++;
}
else
{
continue;
}
}
printf("%s",rs);
return 0;
}
but gives weird output for pass#word. where am i going wrong exactly?
printf("%s",rs); expects rs to be a pointer to a string. Yet without a certain null character in the data pointed to by rs, the result is undefined behavior or in OP's case, "weird output".
A simple solution is
rs[c] = '\0'; // add this after the loop
printf("%s",rs);
Another important one is to avoid buffer overruns - use a width limit.
// scanf("%s",s);
scanf("%99s",s);
Code has other weaknesses, yet this are the key ones for now.

i am trying to do string reverse in a diffrent way

**i am trying to reverse a string so what i am trying is to take the string to its last position and from there i am storing it to a new character array and printing that but not getting desired output **
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char c[10];
printf("Enter the string:\n");
gets(c);
rev(c);
return 0;
}
void rev(char c[])
{
int i = 0,j = 0;
char s[10];
while(c[j] ! = '\0')//reaching to end of string
{
j++;
}
while(s[i] ! = '\0')
{
s[i] = c[j];//copying string c from end into string s from begining
i++;
j--;
}
s[i+1]='\0';
printf("The string after reverse: %s",s);//printing reversed string
}
while(s[i] ! = '\0')
In above line s[i] is uninitialized and hence you are invoking undefined behaviour by accessing uninitialized value and thus incorrect result.
To fix this, you can rewrite the condition as:
while(j >= 0)
Apart from these, for sane result, you need following two changes:
The final termination should be re-written as:
s[i]='\0';
The initial value of j should be decremented by 1. (As c[j] would point to the null character)
as i is now already pointing past the size of c string.
problem is when you use gets() the buffer is usually dirty. I would suggest you use fflush(stdin) before the gets().
Also the last line where you say s[i+1] = '\0' should be s[i] = '\0' the i already was incremented by one after the last execution of the loop.
And as said above it shouldnt be while (s[i] != '\0')
s is not initialized so God knows whats in there. make it like while ( j >=0) and it should work.

infinite loop on printing 2D array

#include <stdio.h>
void main()
{
char plaintext[50];
char key[20];
int plain=0,max1=0,max2=0; // max2 amount of coloumn n max1 for row on chip
char chip[30][30];
int i,j,k=0,c=0;
printf("Enter key :");
scanf("%s",&key);
for(i=0;key[i]!='\0';i++)
{
max2++;
}
printf("Enter plaintext :");
scanf("%s",&plaintext);
for( i = 0; plaintext[i] != '\0'; i++ )
{
plain++;
}
if (plain%max2==0)
max1=plain/max2;
else
max1=plain/max2+1;
while(plaintext[k]!='\0')
{
for (i=0;i<max1;i++)
{
for (j=0;j<max2;j++)
{
chip[i][j]=plaintext[k];
k++;
}
}
}
printf("%s",chip[0][0]);
}
1st im trying to move the string on plain (1D array) into chip(2d array) with dynamic array on the 2D but when im trying to run this code it show nothing than stopped working.. is there anything goes wrong with my 2D array?
I compiled it on Linux (after omitting the void because in Linux main has to return a value) and I got "Segmentation fault". I guess it is because of printf("%s",chip[0][0]);, it should be printf("%s",chip[0]);
I mean chip[0][0] returns a specific character in the chip[0] and you want to print the first string in chip array, right?

Resources