Strange characters in c - c

This is my source code:
#include <stdio.h>
#include <string.h>
void main()
{
int broj_znakova,i=0;
char niz1[81],niz2[81];
printf("Enter something, for end Ctrl/c \n\n");
while(fgets(niz1,81,stdin)!=NULL)
{
continue;
}
printf("You just enter: %s \n",niz1);
printf("This string is long %d\n",(strlen(niz1)-1));
strcpy(niz1,niz2);
printf("niz2 is %s\n",niz2);
if(strcmp(niz1,niz2)==0)
{
printf("niz1 and niz2 is same\n");
}
else
{
printf("niz1 != niz2\n");
}
while(niz1[i]!='\n')
{
if(niz1[i]==' ')
{
broj_znakova ++;
i=i+1;
}
}
printf("Spaces in string = %d\n",broj_znakova);
}
When i press Ctrl/c i got a bunch of strange characters, can someone help???
I google something about flushing but i'm new :)

The contents of niz2 is not initialized. It will result in undefined behavior. Perhaps you meant to copy niz1 to niz2. If so, then you need to reverse the parameters in the strcpy call. With strcpy, the first parameter is the target.
Note too that the variable broj_znakova is never initialized.

C does not "zero out" information in memory (in general) so when it allocates variables, you get whatever is there in memory at the time (whether it is logically readable as words or not), if you are printing something without the system knowing this is a string then it will keep printing until it encounters a NULL terminating character, if there is none, it tries to print whatever is in memory and this produces the weird characters.

On this line
strcpy(niz1,niz2);
I believe your parameters are reverse, it should be strcpy(niz2, niz1); The strange characters you are seeing is because niz2[81] has memory allocated, but it's not "filled in". So you get whatever 'magical' data that allocation may contain. That is, until you put something in it, or do memset, etc.

Related

How to make a conditional loop from "Yes, no" question by comparing String with pointer initiation? [C Programming]

int main(int argc, char* argv[]) {
char* string; //local variable for a character
string = (char*)malloc(sizeof(char));
char* yes = "yes";
printf("Do you want to play (y/n)?");
scanf_s("%s", string);
if (strcmp(yes, string) == 0) {
printf("Hello welcome...");
}
Above is my code. Essentially, I want to make a loop asking for the user to input yes, y to continue; n, no to discontinue. But I simplify it for the sake of simple codes. The program just output the question, I press enter yes and enter then it stops.
I cant figure out a way to do it using array syntax( char string[] way, although array and malloc are basically the same) so I use pointer and malloc instead.
I'm going mad because this is bugging me so much. The practice assignment only asks to input character 'y' 'n' using %c but i want to do it the %s.
Really appreciate any help, im really stuck now. Thank you so much
Your code has two significant problems. First, if you want to input a string of characters, your malloc call needs to allocate space for more than one character; you should allocate the maximum number of characters you think the user's input will contain plus one - strings in C have a zero (nul) character at the end, to mark the end of the string).
Second, when you use the scanf_s function to read in a string (using the %s format specifier, as you have done), then you need to add additional parameters (the size of the target string buffer) after each string argument.
Here's a modified version of your code with these (and a few other) corrections:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
char* string = malloc(5); //local variable for a character string (up to 5 chars)
char* yes = "yes";
printf("Do you want to play (y/n)?");
scanf_s("%s", string, 5);
if (strcmp(yes, string) == 0) {
printf("Hello welcome...");
}
free(string); // Don't forget to release the memory!
return 0; // Conventionally, return 0 for success or non-zero on error
}
Note 1: Each and every call to malloc (or calloc) should be paired with a call to free to release the allocated memory, or you will end up with memory leaks.
Note 2: Please read this post: Do I cast the result of malloc?
Note 3: Although most (all?) C compilers will not insist on it, it is good practice to explicitly add a return 0; (for success) statement at the end of the main function.
Please feel free to ask for any further clarification and/or explanation.

Given a string write a program to generate all possible strings by replacing ? with 0 and 1?

I have written this code it is working fine for a?b?c? and a?b?c?d? but for a?b?c?d?e? it is giving one additional garbage value at the end. At the end of s there is '\0' character attached then why and how is it reading that garbage value. I tried to debug it by placing printf statements in between the code but couldn't resolve it. please help.
#include<stdio.h>
void print(char* s,char c[],int l)
{
int i,j=0;
for(i=0;s[i]!='\0';i++)
{
if(s[i]=='?')
{
printf("%c",c[j]);
j++;
}
else
printf("%c",s[i]);
}
printf(", ");
}
void permute(char *s,char c[],int l,int index)
{
if(index==l)
{
print(s,c,l);
return;
}
c[index]='0';
permute(s,c,l,index+1);
c[index]='1';
permute(s,c,l,index+1);
}
int main()
{
char s[10],c[10];
printf("Enter a string.");
scanf("%s",s);
int i,ct=0;
for(i=0;s[i]!='\0';i++)
{
if(s[i]=='?')
ct++;
}
permute(s,c,ct,0);
return 0;
}
My output was like this :-
a0b0c0d0e0♣, a0b0c0d0e1♣,
...and so on.
As we can see from your code, with an array defined like char s[10] and the input being
a?b?c?d?e?
is too big an input to be held in s along with the null-terminator by
scanf("%s",s);
You need to use a bigger array. Otherwise, in attempt to add the terminating null after the input, the access is being made to out-of-bound memory which invokes undefined behaviour.
That said, never allow unbound input to the limited-sized array, always use the field-width to limit the input length (in other words, reserve the space for null-terminator), like
scanf("%9s",s);
The code is producing the correct output here, but note that it has undefined behavior for strings of size greater than or equal to 10 chars, because that's the size of your buffer.
So, for a?b?c?d?e? you need a buffer of at least 11 characters, to account for the null terminator. You should make s bigger.
See actually in C what happens in String is that everytime it appends a '\0' character at last.
Now notice in C there is nothing called string.
It's array of characters.
So if you have defined like this-
char s[10]
This actually accepts an array of less than of 9 characters as the last one will be the '\0' character.
If you add more than 9 character it will give erroneous output.

Replacement of a word within a string

I am trying to replace a word within a sentence with another word.
For ex. if str1="strong" and str2="weak", then the 1st string in str should get changed to "If the core is weak, you can't go wrong".
I am getting segmentation fault(core dumped) error.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void func(char *str,char *str1,char *str2,int l1,int l2)
{
int i,m,j,c;
for(i=0;*(str+i)!='\0';i++)
{
if(*(str+i)==*str1)
{
for(m=i,j=0;j<l1;m++,j++) /*checking the equality of the two words*/
{
if(*(str+m)!=*(str1+j))
break;
else
c=1;
}
if(c==1)
{
for(j=i;*(str+j)!='\0';j++)
*(str+j+l2-l1)=*(str+j);
for(m=0,j=i;(*(str2+m)!='\0');j++,m++)
*(str+j)=*(str2+m);
}
}
}
}
int main()
{
char *str[]={
"If the core is strong, you can't go wrong",
"Canada's wonder of the world",
"Processing a sorted array",
"Was that a joke?",
"I wanna be a millionaire",
"Your post is not properly formatted"
};
int i,l1,l2,k,j;
char str1[10],str2[10];
l1=strlen(str1);
l2=strlen(str2);
printf("Enter string 1 : ");
scanf("%s",str1);
printf("\nEnter string 2 : ");
scanf("%s",str2);
for(k=0;k<=5;k++)
func(str[k],str1,str2,l1,l2);
for(i=0;i<6;i++)
{
printf("\n");
for(j=0;*(str[i]+j)!='0';j++)
printf("%c",*(str[i]+j));
}
return 0;
}
char *str[]={
"If the core is strong, you can't go wrong",
"Canada's wonder of the world",
"Processing a sorted array",
"Was that a joke?",
"I wanna be a millionaire",
"Your post is not properly formatted"
};
This creates a array of character pointers and each pointer points to a string literal and if you modify a string literal it will result in segmentation fault since it is in read-only memory. this is the reason that you are getting segmentation fault.
Do check your logical errors too in your code.
Your code is unfortunately wrong on many levels. Others have already pointed out the string literal issue, and the issue with strlen() before scanf() in main(), but there is more wrong:
1. You try to edit the string in-place. What happens if you replace a sub-string with a longer string? You try to move the string forward. But that means you write past the end of the memory allocated to the string. This is undefined behaviour and may crash.
2. In func():
[snip]
if(c==1)
{
for(j=i;*(str+j)!='\0';j++)
*(str+j+l2-l1)=*(str+j);
for(m=0,j=i;(*(str2+m)!='\0');j++,m++)
*(str+j)=*(str2+m);
}
You iterate until the source string is null-terminated, but you don't copy the null-terminator! Later on, you try to printf() the string (character by character, for some unfathomable reason, also not checking for a null-terminator but for an ASCII '0'...), which will then crash due to the lack of null-termination.
To solve your issues, you can do the following:
1. Walk through the string using strstr() to find the sub-string to replace. Count the number of occurrences of the sub-string.
2. Use strlen() in func() to determine the length of the sub-string and the replacement. Multiply the difference by the number of occurrences of the sub-string to find how much longer or shorter your new string will be. Add the difference to strlen() of the original string to find out how much memory to allocate (Remember to allocate an extra byte for null-termination).
3. Allocate the needed memory with malloc().
4. Use a combination of strcpy()/strncpy()/memmove()/strstr()/whatever standard library functions you need to assemble your new string.

Simple if statement in c that doesn't work

Can anyone tell me why this code crashes? It's simple, if the length of the string is > than 16, ask again for a string. It works if I write control = 1 inside the if statement, but it should work the same without it, 'cause the value of control at that point is 1, am I right?
thans (I'm learning)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(void)
{
int control = 1;
char word[16] ;
printf("Enter a word: ");
while(control == 1)
{
scanf("%s", word);
int len = strlen(word);
printf("Lenght is: %d\n", len);
if (len >= 16)
{
printf("Word lenght to long, enter a new one: ");
}
else
{
control = 0;
}
}
printf("This is the word: %s\n", word );
}
char word[16] allocates 16 bytes of store for a string.
scanf() then reads a string into that store.
If you read in more than the amount of allocated store, memory is corrupted after the end of the store.
That's why you crash.
The problem is that if the user types more than the 15 characters which you have allocated space for, then the computer will merrily write all of them in memory past the end of your array. This will result in "undefined behavior" including crashing your program.
As others have noted, your fundamental problem is that you're allocating 16 characters for the string, and scanf will happily allow you to write past those 16 characters into memory that doesn't belong to you.
Be aware that C will allow you to do this with arrays generally, and understand how standard C strings work: you need to null-terminate them, meaning that you'll always need an extra space in the array for a null-terminating character \0.
There is a way to limit scanf with respect to C strings, using a field width specifier with %s, like so:
char input[17]; // room for 16 characters plus null-terminator
// here scanf will stop after reading 16 characters:
scanf("%16s", input);
With this code, you can safely use scanf to fill your string with no more than 16 characters, and scanf will null-terminate the string for you.
But as others have also noted, scanf is pretty poor at handling user input. It's usually better to use fgets and manage the input string on your own, piece-by-piece.

How to use calloc() in C?

Shouldn't I get an error if my string goes over 9 characters long in this program?
// CString.c
// 2.22.11
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main()
{
char *aString = calloc(10, sizeof(char));
if (aString == NULL)
{
return 1;
}
printf("PLEASE ENTER A WORD: ");
scanf("%s", aString);
printf("YOU TYPED IN: %s\n", aString);
//printf("STRING LENGTH: %i\n", strlen(aString));
}
Thanks
blargman
You don't get a compiler error because the syntax is correct. What is incorrect is the logic and, what you get is undefined behavior because you are writing into memory past the end of the buffer.
Why is it undefined behavior? Well, you didn't allocate that memory which means it doesn't belong to you -- you are intruding into an area that is closed off with caution tape. Consider if your program is using the memory directly after the buffer. You have now overwritten that memory because you overran your buffer.
Consider using a size specifier like this:
scanf("%9s", aString);
so you dont overrun your buffer.
Yes, you got an error. And the most unfortunate part is that you don't know about it. You might know about it later on in the program when something mysteriously crashes (if you're lucky), or when your client's lawyers come to sue you (if you're not).

Resources