Fill char array with input and I dont understand the output - c

So I'm learning the char arrays in C. I wrote a little program which works with functions and reads input from terminal and on EOF will printf the char array.
If I enter, for example: hello my name is and press enter, I receive this output: hello my z Ͳ
I don't understand where the z Ͳ comes from. Can someone explain it to me?
#include <stdio.h>
const int MAXLENGTH = 10;
int getLine(char[], int);
int main(void) {
char inputString[MAXLENGTH];
getLine(inputString, MAXLENGTH);
printf("%s", inputString);
return 0;
}
// Functions:
int getLine(char destArray[], int length) {
int returnLength;
int input;
for (int i = 0; i < length - 1; i++) {
if ((input = getchar()) != EOF) {
destArray[i] = input;
returnLength = i;
}
}
return returnLength;
}

There are multiple problems in your code:
you do not store a null terminator at the end of the destination array in getLine().
you should stop read from stdin when you get a newline ('\n') or an EOF value.
Here is a modified version:
#include <stdio.h>
const int MAXLENGTH = 10;
int getLine(char[], int);
int main(void) {
char inputString[MAXLENGTH];
getLine(inputString, MAXLENGTH);
printf("%s\n", inputString);
return 0;
}
// Functions:
int getLine(char destArray[], int length) {
int i, c;
for (i = 0; i < length - 1; i++) {
c = getchar();
if (c == EOF || c == '\n')
break;
destArray[i] = c;
}
destArray[i] = '\0';
return i;
}
Running this program will show that hello my name is does not fit in the destination array as the program's output will be hello my
In your program, you were not storing anything beyond the end of the buffer, because you correctly test i < length - 1, but printf did read beyond the 9-th byte set by getLine() and printed whatever contents was in memory at those addresses until it finds a null byte, which is undefined behavior. The weird output is a benign side effect of undefined behavior, the program could have crashed too. The bytes in the memory probably correspond to values stored in the stack for the main() function local frame and return address. Different compilers, different platforms or even different invocations of the same program could produce different output (the latter may seem unlikely, but would happen on OS/X because of stack randomisation).

Related

C language alphanumeric check for bad chars

I have this C code fully working:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdint.h>
int isAlphaNum(char *str) {
for (int i = 0; str[i] != '\0'; i++)
if (!isalnum(str[i]))
return 0;
return 1;
}
int main() {
char *user_string = "abcdedf0123456789ABCD";
if (isAlphaNum(user_string)) {
printf(" is valid \n");
} else {
printf(" is not valid \n");
}
printf(" \n end \n");
return 0;
}
the following is copied from terminal:
but when I receive input via socket like this:
90a41ae8477a334ba609e06cujdikj#%&%$#$Dkdfsノ,ᅵハ"]￘モ {ᆳf
or
▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒814
the program crashes
at this part:
for (int i = 0; str[i] != '\0'; i++)
if (!isalnum(str[i]))
I used the function by #chqrlie and works:
edited
int isAlphaNum(const char *str) {
//this message is printed , then craches
printf("pass isAlphaNum userinput = %s\n" , str);
while (*str) {
if (!isalnum((unsigned char)*str++))
return 0;
}
return 1;
}
if (isAlphaNum(userinput)) {
printf(" success ;) \n");
}
all ok now
thanks for the help
There is an issue in your code, but it is unlikely to cause the problem on GNU/linux systems, but might on other ones: isalnum(str[i]) has undefined behavior if str[i] has a negative value, which is possible if the string contains 8-bit bytes and the char type is signed by default. isalnum() should only be passed values of the type unsigned char or the special negative value EOF.
The function should be written this way:
#include <ctype.h>
int isAlphaNum(const char *str) {
while (*str) {
if (!isalnum((unsigned char)*str++))
return 0;
}
return 1;
}
Your remark about receiving input via socket prompts me to suspect that you are not null terminating the string received via a socket. This could cause isAlphaNum() to read beyond the end of the array and cause a segmentation fault if there is no null byte until the end of the memory mapped area (which used to be called a segment in ancient Multics systems).

Strange behaviour of printf with array when passing pointer to another function

To study for the exam we are trying to do some exercise from past exams.
In this exercise we get a header file and we have to create a function that read an input file and print onto the stdout only the parts of strings that do not contain digits.
(We have to pass the pointer of the string red to the main function).
We tried to do it with a an array but when printing the first word is empty or has strange characters. Instead doing a malloc allocation works fine.
What is also strange is that printing before everything an empty string will fix the code.
Therefore we don't understand why using an array of char the first word is not printed correctly, although it is saved in the buffer.
Including a printf before the while loop in the main function will reset the problem.
Using dynamic allocation (malloc) and not static allocation (array) will fix the print.
Iterating over the whole array and set all the memory to 0 does not fix the problem.
Therefore the pointer is correct as with printing an empty string it prints it correctly, but I really cannot understand what cause the issue.
Question are:
How it is possible that printing an empty string the print is correct?
Array is allocated on the stack therefore it is deallocated when the program exit the scope, why is only the first broken and not all the words?
#include "word_reader.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
const char * read_next_word(FILE * f) {
char buffer[WORD_MAX_LEN];
char * word = buffer;
for (int i = 0; i < WORD_MAX_LEN; ++i)
buffer[i] = 0;
//char * buffer = malloc(sizeof(char) * WORD_MAX_LEN);
int found = 0;
int c = 0;
int i = 0;
while (!found && c != EOF) {
while ((c = fgetc(f)) != EOF && isalpha(c)) {
found = 1;
buffer[i] = c;
++i;
}
buffer[i] = '\0';
}
if (found) {
return word;
//return buffer; // when use malloc
}
return 0;
}
int main(int argc, char * argv[]) {
FILE * f = fopen(argv[1], "r");
if(!f) {
perror(argv[1]);
return EXIT_FAILURE;
}
const char * word = 0;
//printf(""); // adding this line fix the problem
while ((word = read_next_word(f))) {
printf("%s\n", word);
}
fclose(f);
return 0;
}
the header file contain only the read_next_word declaration and define WORD_MAX_LEN to 1024. (Also include
the file to read (a simple .txt file)
ciao234 44242 toro
12Tiz23 where333
WEvo23
expected result:
ciao
toro
Tiz
where
WEvo
actual result
�rǫs+)co�0�*�E�L�mзx�<�/��d�c�q
toro
Tiz
where
WEvo
the first line is always some ascii characters or an empty line.

Get text while not EOF

Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define N 256
int main(int argc, const char * argv[]) {
char testo[N];
int i;
printf("PER TERMINARE L'INSERIMENTO PREMERE CTRL+Z oppure CTRL+D \n");
for(i=0;i<N;i++)
{
scanf("%c",&testo[i]);
/* if(testo[i]=='h' && testo[i-1]=='c')
{
i--;
testo[i]='k';
}
if(testo[i]==testo[i-1])
{
i--;
} */
if(testo[i]==EOF)
{
break;
}
}
puts(testo);
return 0;
}
When the code in /* ... */ is compiled, I can't stop the insert of text with EOF, but when the code is built and run as shown here, the EOF works.
Does anyone have any idea what the problem is?
You're testing for EOF incorrectly. With scanf(), you need to look at the return value. In fact, with almost all input functions, you need to test, if not capture and test, the return value.
Superficially, you need:
for (i = 0; i < N; i++)
{
if (scanf("%c", &testo[i]) == EOF)
break;
…
}
However, in general, you should check that scanf() made as many successful conversions as you requested, so it is better to write:
for (i = 0; i < N; i++)
{
if (scanf("%c", &testo[i]) != 1)
break;
…
}
In this example, it really won't matter. If you were reading numeric data, though, it would matter. The user might type Z instead of a number, and scanf() would return 0, not EOF.
To detect EOF, check the result of scanf()
if scanf("%c",&testo[i]) == EOF) break;
Note: testo[] may not be null character terminated. To print as a string, insure it is.
char testo[N];
int i;
// for(i=0;i<N;i++) {
for(i=0;i<(N-1);i++) {
if (scanf("%c",&testo[i]) == EOF) break;
}
testo[i] = '\0'; // add
puts(testo);
To stop at end of file, check the return value from scanf:
scanf returns the number of inputs correctly parsed. In your case, %c reads a byte from the stream correctly as long as end of file has not been reached. if (scanf("%c",&testo[i]) != 1) break; will do.
Yet using scanf to read one byte at a time from the input stream is overkill. The idiomatic way to do this in C is using the getchar() or the getc() function. The return value must be stored in an int variable and has special value EOF upon end of file.
You should also make the array 1 byte longer and store a null byte at the end to make it a C string, as expected by puts.
Here is a modified version of your program:
int main(int argc, const char *argv[]) {
char testo[N+1];
int i;
printf("PER TERMINARE L'INSERIMENTO PREMERE CTRL+Z oppure CTRL+D\n");
for (i = 0; i < N; i++) {
int c = getchar();
if (c == EOF)
break;
testo[i] = c;
/* ... further processing ... */
}
testo[i] = '\0';
puts(testo);
return 0;
}

segmentation fault occur while reversing the string

Below is my piece of code, I don't understand why it always gives me the segmentation fault:
#include <stdio.h>
void reverse(void);
int main ()
{
printf("enter the text");
printf("\n");
reverse();
printf("\n");
return(0);
}
void reverse(void)
{
char c;
if((c=getchar()) != '\n')
{
reverse();
}
putchar(c);
}
In my opinion I have done everything correctly, what is the mistake?
The code works fine as long as you enter a newline. Perhaps you are terminating your input with EOF (usually bound to Ctrl+D) without feeding it a newline before, and in that case, the code will never see a newline and there will be a stack overflow due to infinite recursion.
So, you should check that getchar() doesn't return EOF. Also, getchar() returns int, not char - this is important for portability and to make sure that comparison with EOF works as expected.
Here's the code after addressing these issues:
#include <stdio.h>
void reverse(void);
int main (void) {
printf("enter the text\n");
reverse();
printf("\n");
return 0;
}
void reverse(void) {
int c;
if ((c=getchar()) != '\n' && c != EOF) {
reverse();
}
if (c != EOF) {
putchar(c);
}
}
Your program compiled and ran fine on my setup: latest stable gcc on Ubuntu 14.04.2 LTS 64-bit.
Here is another version using a different approach (namely the fgets function). See if it works for you:
#include <stdio.h>
#include <string.h>
void reverse_str( char * );
int main()
{
char input[1024];
printf("Enter text: ");
fgets(input, sizeof(input), stdin);
reverse_str(input);
printf("Reversed string: %s\n", input);
return 0;
}
void reverse_str(char *to_reverse)
{
char temp[1024];
int count = strlen(to_reverse) - 1; //Exclude newline introduced with fgets
int i=0;
for( i=count; i>=0; i-- ){
temp[i] = to_reverse[count - i - 1]; //Subtract 1 to not include the new line introduced by fgets
}
temp[count+1] = '\0';
strcpy(to_reverse, temp);
}
Your code seems to failing because of the nasty characters of getchar()..In most of the system it should work but I think your compiler is trying to access the memory saved beyond the array & hence generating segmentation fault...Can you please make sure if you give '\0' in place of '\n', it is working or not..I think the problem is that your machine is not able to detect the '\n' given from your keyboard & hence keep on going into recursion mode & stack is overflown before the recursion ends & when stack is overflown, it is trying to access unauthorised memory & hence segmentation fault occurs
Try this
#include <stdio.h>
#include <string.h>
char str[] = "Hello World";
size_t length;
int count = 0;
void reverse(char* a, char* b){
// static int count = 0;
char temp;
if (count < length/2){
count++;
reverse(str + count, str + (length - 1) - count);
}
temp = *a;
*a = *b;
*b = temp;
}
int main(){
length = strlen(str);
reverse(str, str + length - 1);
printf("%s", str);
return 0;
}

read string of character and assign it to an array

I don't know how to work with scanf and get the input of it for the entry of the function readBigNum I want to make array until the user entered the Enter and also I want to write a function for assigning it into an array and return the size of the large number
I want readBigNum to exactly have the char *n but I can not relate it in my function
#include <stdio.h>
int readBigNum(char *n)
{
char msg[100],ch;
int i=0;
while((ch=getchar())!='\n')
{
if(ch!='0'||ch!='1'||ch!='2'||ch!='3'||ch!='4'||ch!='5'||ch!='6'||ch!='7'||ch!='8'||ch!='9')
return -1;
msg[i++]=ch;
}
msg[i]='\0';
i=0;
return i;
}
int main()
{
const char x;
const char n;
n=scanf("%d",x);
int h=readBigNum(&n);
printf(h);
}
If I understand your question correctly, you want to implement a function that will read numbers from stdin storing them in a buffer. If a non-number is encountered, you want to return -1. If a new-line is encountered, you want to return the number of characters that were read. If that's correct, you'll probably want your code to look something like the following:
#include <stdio.h>
int readBigNum(char* n)
{
char ch;
int i=0;
while ((ch = getchar()) != '\n') {
if (ch < '0' || ch > '9') {
return -1;
}
n[i++] = ch;
}
n[i] = '\0';
return i;
}
int main(void) {
char buf[100];
int bytes = readBigNum(buf);
printf("%s\n", buf);
printf("%d\n", bytes);
};
The main differences from your implementation
The array to be populated is initialized in main and passed to the readBigNum function. This is a little simpler than having the function control the memory, in which case you would need likely need to deal with malloc and free. Even with this, you run the risk of a buffer overrun and will likely want to take additional precautions to prevent that.
The function does not set i to 0 before returning it. The original code could never return a value other than -1 (on error) or 0, which didn't appear to be the intent.
This code doesn't use scanf. Given your description of what you wanted to accomplish, using scanf didn't appear to be a good fit, however if you provide more information on why you were calling it might help to inform this answer.
The printf call was incorrect, it has been updated to print the number of bytes returned, and an additional printf call was added to print the updated buffer.
Remember that getchar() returns type int, not char. This is because the function may return EOF (which is defined as a negative integer with no particular value).
Also, for functions that deal with buffers, it is always a good idea to take an extra argument that describes the size of the array. This helps reduce buffer overruns because you know how far you can go. With your existing function, if the user types more than 100 characters, your buffer is overrun.
#include <stdio.h>
#include <ctype.h>
int readBigNum(char *n, size_t len)
{
int ch;
int i = 0;
// we make sure 'i' is less than 'len - 1' to leave space for '\0'
while((ch = getchar()) != EOF && i < (len - 1))
{
if (ch == '\n') // stop on linefeed
break;
else if (!isdigit(ch))) // abort on invalid character
return -1;
else
n[i++] = (char) ch;
}
msg[i] = '\0';
return i;
}
int main(void)
{
char buf[100];
int result = readBigNum(buf, sizeof buf);
if (result > 0)
printf("Length %d : %s\n", result, buf);
else
printf("Invalid number!\n");
}

Resources