My program written in C below is running to a certain point. However, it stops in the middle of, what I would deem, error-less code. Coming from Java, I'm a newbie with C so any help would be much appreciated.
#include <stdio.h>
#include <stdlib.h>
void getInput(char *input, const char *rs[]){// Args are the user input and our reserved words array.
printf(">>"); fgets(input, 1000, stdin);// Getting our normal command
int i;
for(i = 0; i < (int)sizeof(rs); i++){
if(strcmp(input, rs[i]) != 0){
printf("You said: %s", input); //PROGRAM BREAKS AFTER THIS LINE
}
}
printf("Size of \"input\" is: %d\n", sizeof(input));// Just checking the size of input
free(input);// Deallocating input since we won't need it anymore.
}
int main(){
char *input = malloc(500 * sizeof(char));// Command line input
const char *rs[1];// Reserved words array.
rs[0] = "print";
getInput(input, rs);
getch();
}
A couple of problems, mostly stemming from treating C as if it had strings and arrays like Java. It doesn't, it just has blocks of bytes and some functions to do string-like and array-like things with them.
So firstly, malloc(500 * sizeof(char)) allocates 500 bytes (sizeof char is 1 by definition). Later you fgets(input, 1000...) on those 500 bytes. Not good.
char *rs[1] allocates an array of 1 character pointer. It does not allocate any memory for any strings. rs[0] = "print" is OK because "print" allocates 6 bytes and the assignment makes rs[0] point to them. But then you pass rs to the function getInput and call sizeof on it, which gives you the size of a single pointer (probably 4 or 8 bytes) because C doesn't keep array dimensions either--It just passes a pointer to the start of the array. You need to pass the length yourself.
You aren't checking the return value of fgets(). And even if you weren't reading 1000 bytes into a 500-byte buffer and fgets were working perfectly, your strcmp() will always fail because fgets() includes the newline in the string.
Finally, sizeof(input) is another size-of-pointer, not an array dimension. you probably mean strlen(input)?
Related
I am new to coding. As a practice problem, I wrote a program to sort strings as alphabetically, as in a dictionary. My program takes as input:
(a) The number of strings the user has in mind
and (b) The strings, one by one, each terminated by pressing the enter key.
It stores the initial input in a buffer array of size MAXSTR and simultaneously counts the number of characters. Then it creates allocates memory of requisite size at memory location input[i] and copies the buffer to that location. It also creates an index array, with array elements having value of 0, 1, 2 ... each corresponding to one the 0th string, 1st string, 2nd string ... and so on. The function dictsort sorts the index array based on the alphabetical position of the corresponding string.
My program runs smoothly on Linux machines. However, on Windows, it compiles alright, but while running the executable, it ends abruptly while executing the line "input[i]=(char)malloc(jsizeof(char));". If any of you guys can indicate what is happening it will be of great help. Note that my problem is with the main function only. The sorting functions work fine, and hence those are not either included or commented out from below code.
#define MAX 10000
#define MAXSTR 100
#include<stdio.h>
#include<stdlib.h>
//int dictsort(char **mainarray, size_t *indexarray, size_t elementcount);
//int strcompare(char* str1, char* str2);
//int getvalue(int input);
int main(void){
size_t n, i, j,k;
char buffer[MAXSTR];
int c;
size_t *index;
char **input;
printf("Input number of elements:\t");
scanf("%ld", &n);
n=n<MAX ? n : MAX;
index=(size_t*)malloc(n*sizeof(size_t));
getchar(); // flush the newline after scanf
for(i=0;i<n;++i){
index[i]=i;
printf("Input element %ld:\t", i+1);
j=0;
while(((c=getchar())!=EOF) && (c!='\n') && (c!='\0') && (j<MAXSTR-1)){
buffer[j]=c;
++j;
}
buffer[j]='\0';
printf("Upto 1\n"); //program comes upto here
input[i]=(char*)malloc(j*sizeof(char));
printf("Upto 2\n"); //never reaches here
for(k=0;k<j+1;++k){
input[i][k]=buffer[k];
}
}
//dictsort(input, index, n); //disabled for debugging
printf("The sorted array is: \n");
for (i=0;i<n;++i){
printf("%s ", input[index[i]]);
}
for(i=0;i<n;++i){
free(input[i]);
}
free(index);
return 0;
}
First error:
You are allocating memory for index and input[i], but not for input itself. This means that you are dereferencing an uninitialized pointer on the following line:
input[i]=(char*)malloc(j*sizeof(char));
This will invoke undefined behavior, which explains why it crashes on that line on one platform, but works on another platform.
Second error:
The line
input[i]=(char*)malloc(j*sizeof(char));
will not allocate sufficient space for storing the string. Since j is the size of the string without the terminating null character, you must allocate j+1 bytes instead.
Due to not allocating a sufficient number of bytes for the string, the following loop will access the memory buffer input[i] out of bounds:
for(k=0;k<j+1;++k){
input[i][k]=buffer[k];
}
This will invoke undefined behavior.
Third error:
Another source of undefined behavior in your program is the following line:
scanf("%ld", &n);
The correct conversion format specifier for size_t is %zu, not %ld. See the documentation of the function scanf for further information.
On 64-bit Microsoft Windows, a long has a width of 4 bytes, but a size_t has a width of 8 bytes. Therefore, because you are using the format specifier for long instead of size_t, the function scanf is probably only writing to half of the variable n, leaving the other half of the variable uninitialized. This is likely to cause trouble when you read the value of n later in the program.
Most compilers will warn you about using the wrong scanf conversion format specifiers, assuming that you enable all compiler warnings. You may want to read this:
Why should I always enable compiler warnings?
For an instance if I store ABCDE from scanf function, the later printf function gives me ABCDE as output. So what is the point of assigning the size of the string(Here 4).
#include <stdio.h>
int main() {
int c[4];
printf("Enter your name:");
scanf("%s",c);
printf("Your Name is:%s",c);
return 0;
}
I'll start with, don't use int array to store strings!
int c[4] allocates an array of 4 integers. An int is typically 4 bytes, so usually this would be 16 bytes (but might be 8 or 32 or something else on some platforms).
Then, you use this allocation first to read characters with scanf. If you enter ABCDE, it uses up 6 characters (there is an extra 0 byte at the end of the string marking the end, which needs space too), which happens to fit into the memory reserved for array of 4 integers. Now you could be really unlucky and have a platform where int has a so called "trap representation", which would cause your program to crash. But, if you are not writing the code for some very exotic device, there won't be. Now it just so happens, that this code is going to work, for the same reason memcpy is going to work: char type is special in C, and allows copying bytes to and from different types.
Same special treatment happens, when you print the int[4] array with printf using %s format. It works, because char is special.
This also demonstrates how very unsafe scanf and printf are. They happily accept c you give them, and assume it is a char array with valid size and data.
But, don't do this. If you want to store a string, use char array. Correct code for this would be:
#include <stdio.h>
int main() {
char c[16]; // fits 15 characters plus terminating 0
printf("Enter your name:");
int items = scanf("%15s",c); // note: added maximum characters
// scanf returns number of items read successfully, *always* check that!
if (items != 1) {
return 1; // exit with error, maybe add printing error message
}
printf("Your Name is: %s\n",c); // note added newline, just as an example
return 0;
}
The size of an array must be defined while declaring a C String variable because it is used to calculate how many characters are going to be stored inside the string variable and thus how much memory will be reserved for your string. If you exceed that amount the result is undefined behavior.
You have used int c , not char c . In C, a char is only 1 byte long, while a int is 4 bytes. That's why you didn't face any issues.
(Simplifying a fair amount)
When you initialize that array of length 4, C goes and finds a free spot in memory that has enough consecutive space to store 4 integers. But if you try to set c[4] to something, C will write that thing in the memory just after your array. Who knows what’s there? That might not be free, so you might be overwriting something important (generally bad). Also, if you do some stuff, and then come back, something else might’ve used that memory slot (properly) and overwritten your data, replacing it with bizarre, unrelated, and useless (to you) data.
In C language the last of the string is '\0'.
If you print with the below function, you can see the last character of the string.
scanf("%s", c); add the last character, '\0'.
So, if you use another function, getc, getch .., you should consider adding the laster character by yourself.
#include<stdio.h>
#include<string.h>
int main(){
char c[4+1]; // You should add +1 for the '\0' character.
char *p;
int len;
printf("Enter your name:");
scanf("%s", c);
len = strlen(c);
printf("Your Name is:%s (%d)\n", c, len);
p = c;
do {
printf("%x\n", *(p++));
} while((len--)+1);
return 0;
}
Enter your name:1234
Your Name is:1234 (4)
31
32
33
34
0 --> last character added by scanf("%s);
ffffffae --> garbage
I am currently learning C, and so I wanted to make a program that asks the user to input a string and to output the number of characters that were entered, the code compiles fine, when I enter just 1 character it does fine, but when I enter 2 or more characters, no matter what number of character I enter, it will always say there is just one character and crashes after that. This is my code and I can't figure out what is wrong.
int main(void)
{
int siz;
char i[] = "";
printf("Enter a string.\n");
scanf("%s", i);
siz = sizeof(i)/sizeof(char);
printf("%d", siz);
getch();
return 0;
}
I am currently learning to program, so if there is a way to do it using the same scanf() function I will appreciate that since I haven't learned how to use any other function and probably won't understand how it works.
Please, FORGET that scanf exists. The problem you are running into, whilst caused mostly by your understandable inexperience, will continue to BITE you even when you have experience - until you stop.
Here is why:
scanf will read the input, and put the result in the char buffer you provided. However, it will make no check to make sure there is enough space. If it needs more space than you provided, it will overwrite other memory locations - often with disastrous consequences.
A safer method uses fgets - this is a function that does broadly the same thing as scanf, but it will only read in as many characters as you created space for (or: as you say you created space for).
Other observation: sizeof can only evaluate the size known at compile time : the number of bytes taken by a primitive type (int, double, etc) or size of a fixed array (like int i[100];). It cannot be used to determine the size during the program (if the "size" is a thing that changes).
Your program would look like this:
#include <stdio.h>
#include <string.h>
#define BUFLEN 100 // your buffer length
int main(void) // <<< for correctness, include 'void'
{
int siz;
char i[BUFLEN]; // <<< now you have space for a 99 character string plus the '\0'
printf("Enter a string.\n");
fgets(i, BUFLEN, stdin); // read the input, copy the first BUFLEN characters to i
siz = sizeof(i)/sizeof(char); // it turns out that this will give you the answer BUFLEN
// probably not what you wanted. 'sizeof' gives size of array in
// this case, not size of string
// also not
siz = strlen(i) - 1; // strlen is a function that is declared in string.h
// it produces the string length
// subtract 1 if you don't want to count \n
printf("The string length is %d\n", siz); // don't just print the number, say what it is
// and end with a newline: \n
printf("hit <return> to exit program\n"); // tell user what to do next!
getc(stdin);
return 0;
}
I hope this helps.
update you asked the reasonable follow-up question: "how do I know the string was too long".
See this code snippet for inspiration:
#include <stdio.h>
#include <string.h>
#define N 50
int main(void) {
char a[N];
char *b;
printf("enter a string:\n");
b = fgets(a, N, stdin);
if(b == NULL) {
printf("an error occurred reading input!\n"); // can't think how this would happen...
return 0;
}
if (strlen(a) == N-1 && a[N-2] != '\n') { // used all space, didn't get to end of line
printf("string is too long!\n");
}
else {
printf("The string is %s which is %d characters long\n", a, strlen(a)-1); // all went according to plan
}
}
Remember that when you have space for N characters, the last character (at location N-1) must be a '\0' and since fgets includes the '\n' the largest string you can input is really N-2 characters long.
This line:
char i[] = "";
is equivalent to:
char i[1] = {'\0'};
The array i has only one element, the program crashes because of buffer overflow.
I suggest you using fgets() to replace scanf() like this:
#include <stdio.h>
#define MAX_LEN 1024
int main(void)
{
char line[MAX_LEN];
if (fgets(line, sizeof(line), stdin) != NULL)
printf("%zu\n", strlen(line) - 1);
return 0;
}
The length is decremented by 1 because fgets() would store the new line character at the end.
The problem is here:
char i[] = "";
You are essentially creating a char array with a size of 1 due to setting it equal to "";
Instead, use a buffer with a larger size:
char i[128]; /* You can also malloc space if you desire. */
scanf("%s", i);
See the link below to a similar question if you want to include spaces in your input string. There is also some good input there regarding scanf alternatives.
How do you allow spaces to be entered using scanf?
That's because char i[] = ""; is actually an one element array.
Strings in C are stored as the text which ends with \0 (char of value 0). You should use bigger buffer as others said, for example:
char i[100];
scanf("%s", i);
Then, when calculating length of this string you need to search for the \0 char.
int length = 0;
while (i[length] != '\0')
{
length++;
}
After running this code length contains length of the specified input.
You need to allocate space where it will put the input data. In your program, you can allocate space like:
char i[] = " ";
Which will be ok. But, using malloc is better. Check out the man pages.
This is a very fun problem I am running into. I did a lot of searching on stack overflow and found others had some similar problems. So I wrote my code accordingly. I originally had fscan() and strcmp(), but that completely bombed on me. So other posts suggested fgets() and strncmp() and using the length to compare them.
I tried to debug what I was doing by printing out the size of my two strings. I thought, maybe they have /n floating in there or something and messing it up (another post talked about that, but I don't think that is happening here). So if the size is the same, the limit for strncmp() should be the same. Right? Just to make sure they are supposedly being compared right. Now, I know that if the strings are the same, it returns 0 otherwise a negative with strncmp(). But it's not working.
Here is the output I am getting:
perk
repk
Enter your guess: perk
Word size: 8 and Guess size: 8
Your guess is wrong
Enter your guess:
Here is my code:
void guess(char *word, char *jumbleWord)
{
size_t wordLen = strlen(word);
size_t guessLen;
printf("word is: %s\n",word);
printf("jumble is: %s\n", jumbleWord);
char *guess = malloc(sizeof(char) * (MAX_WORD_LENGTH + 1));
do
{
printf("Enter your guess: ");
fgets(guess, MAX_WORD_LENGTH, stdin);
printf("\nword: -%s- and guess: -%s-", word, guess);
guessLen = strlen(guess);
//int size1 = strlen(word);
//int size2 = strlen(guess);
//printf("Word size: %d and Guess size: %d\n",size1,size2);
if(strncmp(guess,word,wordLen) == 0)
{
printf("Your guess is correct\n");
break;
}
}while(1);
}
I updated it from suggestions below. Especially after learning the difference between char * as a pointer and referring to something as a string. However, it's still giving me the same error.
Please note that MAX_WORD_LENGTH is a define statement used at the top of my program as
#define MAX_WORD_LENGTH 25
Use strlen, not sizeof. Also, you shouldn't use strncmp here, if your guess is a prefix of the word it will mistakenly report a match. Use strcmp.
sizeof(guess) is returning the size of a char * not the length of the string guess. Your problem is that you're using sizeof to manage string lengths. C has a function for string length: strlen.
sizeof is used to determine the size of data types and arrays. sizeof only works for strings in one very specific case - I won't go into that here - but even then, always use strlen to work with string lengths.
You'll want to decide how many characters you'll allow for your words. This is a property of your game, i.e. words in the game are never more that 11 characters long.
So:
// define this somewhere, a header, or near top of your file
#define MAX_WORD_LENGTH 11
// ...
size_t wordlen = strlen(word);
size_t guessLen;
// MAX_WORD_LENGTH + 1, 1 more for the null-terminator:
char *guess = malloc(sizeof(char) * (MAX_WORD_LENGTH + 1));
printf("Enter your guess: ");
fgets(guess, MAX_WORD_LENGTH, stdin);
guessLen = strlen(guess);
Also review the docs for fgets and note that the newline character is retained in the input, so you'll need to account for that if you want to compare the two words. One quick fix for this is to only compare up to the length of word, and not the length of guess, so: if( strncmp(guess, word, wordLen) == 0). The problem with this quick fix is that it will pass invalid inputs, i.e. if word is eject, and guess is ejection, the comparison will pass.
Finally, there's no reason to allocate memory for a new guess in each iteration of the loop, just use the string that you've already allocated. You could change your function setup to:
char guess(char *word, char *jumbledWord)
{
int exit;
size_t wordLen = strlen(word);
size_t guessLen;
char *guess = malloc(sizeof(char) * (MAX_WORD_LENGTH + 1));
do
{
printf("Enter your guess: ");
// ...
As everyone else has stated, use strlen not sizeof. The reason this is happening though, is a fundamental concept of C that is different from Java.
Java does not give you access to pointers. Not only does C have pointers, but they are fundamental to the design of the language. If you don't understand and use pointers properly in C then things won't make sense, and you will have quite a bit of trouble.
So, in this case, sizeof is returning the size of the char * pointer, which is (usually) 4 or 8 bytes. What you want is the length of the data structure "at the other end" of the pointer. This is what strlen encapsulates for you.
If you didn't have strlen, you would need to dereference the pointer, then walk the string until you find the null byte marking the end.
i = 1;
while(*guess++) { i++ }
Afterwards, i will hold the length of your string.
Update:
Your code is fine, except for one minor detail. The docs for fgets note that it will keep the trailing newline char.
To fix this, add the following code in between the fgets and strncmp sections:
if ( guess[guessLen-1] == '\n' ) {
guess[guessLen-1] = '\0';
}
That way the trailing newline, if any, gets removed and you are no longer off by one.
Some list of problems / advices for your code, much too long to fit in a comment:
your function returns a char which is strange. I don't see the
logic and what is more important, you actually never return a value. Don't do that, it will bring you trouble
look into other control structures in C, in particular don't do your exit thing. First, exit in C is a function, which does what it says, it exits the program. Then there is a break statement to leave a loop.
A common idiom is
do {
if (something) break;
} while(1)
you allocate a buffer in each iteration, but you never free it. this will give you big memory leaks, buffers that will be wasted and inaccessible to your code
your strncmp approach is only correct if the strings have the same length, so you'd have to test that first
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.