C - runtime error while printing string(using a pointer) [duplicate] - c

This question already has answers here:
Segmentation fault with scanf and strings in C
(3 answers)
Closed 5 years ago.
I have a problem with a simple C program and i need your help.I declare a string, using a pointer.Using scanf I give it a value from stdin.Later I try printing this string.It all compiles well,but when i run the program, it accepts my string,and when it gets to printing, i recieve a run-time error with return value 3221225477.
Where is the problem here?
I'm using DEV C++ IDE btw.
Note: I also tried doing the same on ideone.com online compiler and it doesn't give a runtime error,but instead of string given in stdin, it prints (null).
Here is the code:
#include <stdio.h>
int main(void)
{
char *string;
scanf("%s", string);
printf("Hello,%s !", string);
return 0;
}

You need to allocate space for the variable string.
For example:
char *string;
int i;
scanf("%d", &i);
string = (char*)malloc(sizeof(char)*i);
And then you can read from input and print the string

Related

Why string[10] containing more 10 character in c? [duplicate]

This question already has answers here:
Char array can hold more than expected
(3 answers)
Why is the gets function so dangerous that it should not be used?
(13 answers)
Closed 28 days ago.
I'm taking array of character size of 10 , but in return it gives me out-range array(10+) string, YOU CAN REFER TO MY CODE
#include<stdio.h>
int main(){
char name[10]; `array of 10 Character`
gets(name); `INPUT: THIS IS BEAUTIFUL WORLD!`
printf("Given string %s", name); `it should print only 10 string in c`
` OUTPUT : Given string THIS IS BEAUTIFUL WORLD! `
return 0;
}
https://en.cppreference.com/w/c/io/gets
char *gets( char *str );
The gets() function does not perform bounds checking, therefore this function is extremely vulnerable to buffer-overflow attacks. It cannot be used safely (unless the program runs in an environment which restricts what can appear on stdin). For this reason, the function has been deprecated in the third corrigendum to the C99 standard and removed altogether in the C11 standard. fgets() and gets_s() are the recommended replacements.

string without null terminator [duplicate]

This question already has answers here:
Undefined, unspecified and implementation-defined behavior
(9 answers)
Using printf with a non-null terminated string
(6 answers)
Closed 1 year ago.
#include <stdio.h>
int main()
{
char as[4];
*as='0';
*(as+1)='1';
*(as+2)='2';
*(as+3)='3';
printf("%s",as);
return 0;
}
The output i got is : 0123.
In the above program i declared an array of size 4 -> char as[4];
and in that i stored 4 chars 0,1,2,3.
Normally if we declare a char array, '\0' will be stored at last (i.e. as[3]='\0');
but i stored '3' in it. how it did not generate error?.
There is absolutely nothing stopping you from using an array of char as an array of char. There could be any number of reasons to want this.
However, C strings are null-terminated by definition. Using the %s specifier in printf tells it to expect a null-terminated string, so your program will (probably) not work correctly unless you give it such a string.

gets() function throw exception? [duplicate]

This question already has answers here:
Why is the gets function so dangerous that it should not be used?
(13 answers)
Closed 4 years ago.
void getInputWith_gets()
{
char firstName[5];
char lastName[5];
printf("Enter your first name: ");
gets(firstName);
printf("Enter your last name: ");
gets(lastName);
printf("Hello, %s, %s\n", firstName, lastName);
}
int main(int argc, char **argv)
{
getInputWith_gets();
//getInputWith_fgets();
system("pause");
return 0;
}
I am using MS Visual Studio 2017, I know the restriction of using the "gets()" function that I have a maximum of 5 chars to be entered but if I entered exactly 5 characters, the console prints correctly(and doesn't print "press any key to continue... due to "system("pause") statment") but the program get stuck at the debugger screen and after the last "printf" statement I get a a red error symbol with a pop-up saying:
"Run-Time Check Failure #2 - Stack around the variable 'lastName' was corrupted."
does this means that the "gets()" function will read 5 exclusive characters only?
You have multiple bugs here:
In ancient, obsolete C where gets existed, you must #include <stdio.h> or otherwise you might get weird run-time behavior, since ancient obsolete C allowed functions with no prototype.
In modern and semi-modern C, the function gets is removed/flagged obsolete and should never be used. See Why is the gets function so dangerous that it should not be used? and also What are the functions from the standard library that must/should be avoided?.
Strings in C are null terminated, meaning you have to leave room for the null terminator.
Also note that the function format void getInputWith_gets() is obsolete style, you should be writing void getInputWith_gets(void).
Overall, it seems you are learning C from a completely outdated source (over 20 years outdated).

C language beginner [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm learning C language following Youtube video and I've got couple of questions.
I typed these below in Xcode
#include<stdio.h>
int main() // 1. why do we have to use this line?
{
char food[] = "tuna";
printf("the best food is %s",food);
strcpy(food,"bacon"); // error here
return 0;
}
When I typed these all, the error come out saying " implicity declaring library function 'strcpy' with type 'char*(char*,const char*)'"
I have no idea what this mean and why it happened? Sorry to bother with question guys but I need your help. Thank you
C is a super great language to learn but because of how low level it is in comparison to python, javascript, etc. There are many manual tasks you need to do including memory management.
But before we get into that, your initial problem is not including the string.h header. Once you include that header, you'll actually get Segmentation Fault.
Below is the explanation on why you'll get the Segmentation Fault.
So when you defined:
char food[] = "tuna"
C created char array with 5 bytes. Why 5? because all strings end with a NULL byte ('\0').
So your string in memory looks like "tuna\0".
Side note:
The importance of the NULL byte is to signify the end of a string. This is super important when you are using a function like printf. Because when printing a string, printf will look for the NULL byte to stop printing.
So this char array has the max size of 5 bytes, 1 being a null byte, so just 4 bytes (chars) of writeable memory.
Then you try to copy the word "bacon" into your 5 byte array.
So strcpy tries to copy the b, then the c, then the o, then the n, then when it tries to terminate the string with a NULL byte, it will seg fault because you're trying to access a byte of memory you don't have access to.
So in order to fix your issue, you could try to strcpy a string that is the same length or shorter than your original string. Or you can look into something like strdup and use pointers.
That code will look like:
#include <stdio.h>
#include <string.h>
int main()
{
char *food = "tuna";
printf("the best food is %s\n",food);
food = strdup("bacon");
printf("the best food is %s\n",food);
return 0;
}
Hope this helps!
I suggest you as exercise to explain me the behavior of this code. You have to understand how "strings" are managed by the C language into the memory.
The code I post below is not right, contains a violation of the space allocated for the variable food. In this case this code doesn't generate a Segmentation Fault, but It might generate such a error!
If you compile the code below with gcc -Wall --pedantic -std=c99 prgname.c
, the compiler doesn't signal warnings nor error, but the code is NOT RIGHT.
PAY ATTENTION! :)
#include <stdio.h>
#include <string.h>
int main() // 1. why do we have to use this line?
{ // --- 'cause is a standard!!! :)
char food[] = "tuna";
char b[]="prova";
printf("the best food is %s - %s - food-size %u\n",food,b,(unsigned int)sizeof(food));
strcpy(food,"fried or roasted bacon"); // error here
printf("the best food is %s - %s - food-size %u\n",food,b,(unsigned int)sizeof(food));
return 0;
}
We have to use main(),this is the function through which execution of C program starts.
For using strcpy()(A predefined function) you need to declare it first. and its declaration is present in string.h so just #include<string.h>
This will resolve your problem.implicit declaring library function 'strcpy' with type'char*(char*,const char*)``
There is one more problem when you declare
char food[]="tuna";
you get only 5 bytes allocated for you,four for character and one more for NULL. When you will try putting baconin it (using strcpy()),which is 6 bytes long. It will cause compiler to create segmentation fault.

program to find length of a string [duplicate]

This question already has answers here:
Program didn't crash when buffer overflow
(2 answers)
Closed 6 years ago.
If I input string of more than size 10 then why is not generating compile time error as I have declared str of size 10? For example I have input welcome to the world, then it is compiling and running with no error.
#include <stdio.h>
#include <conio.h>
int main() {
int i = 0, length;
char str[10];
printf("enter string: ");
gets(str);
while (str[i] !='\0') {
i = i + 1;
}
length = i;
printf("the length of string is %d", length);
}
An input string is a runtime entity. Any computation involving it cannot be performed at compile time, so the best you can do is raise a runtime error.
Furthermore, gets is marked deprecated in C99 and simply removed from C11 because exactly this insecure behavior cannot be prevented: without anyone complaining, you can write beyond array bounds, which is undefined behavior. Use fgets instead, which provides a higher level of security.
Because gets does not take a length parameter it does not know how large your input buffer is.
you can use fgets instead
It is a undefined behaviour. Anything can happen.
Never use gets() because it does not prevent buffer overflowing which is what your program is doing. Use fgets() instead of gets().
fgets() prevent the size of array beyond that.
fgets(array, sizeOfArray, stdin);
Because you defined the string length as 10, so if the value increases the program stops executing, moreover you have not made handling error mechanism for the code. So resulting the following error you mentioned. Use fgets

Resources