Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I was doing an assignment for my C class in school and I hit a little snag.
#include <stdio.h>
char stringToUpper(char * sName )
{
while(*sName != '\0')
{
stringToUpper (* sName);
++* sName;
}
}
int main()
{
char str[50];
char * sName;
printf("Please enter your name ");
scanf("%s", str);
printf("Hello %s ", str);
sName = str;
stringToUpper(sName);
printf("Name in uppercase: %s ", sName);
}
I tried looking for other solutions already, however I found that everyone else's problems were much more advanced than the level I'm at and really just couldn't follow it. I've still a little new at working with pointers and still a little confused about how they work (only a few weeks into the class) so I feel like the issue has something to do with that. I'm almost certain that the issue has something to do with the while statement.
This is the error I get:
Unhandled exception thrown: read access violation.
sName was 0x41.
If there is a handler for this exception, the program may be safely continued.
Thanks in advanced for whatever help I receive.
Your stringToUpper function has some issues:
while(*sName != '\0')
{
stringToUpper (* sName);
++* sName;
}
You could be calling toupper to change to upper case and assigning the value back to *sName instead of having the function call itself. In fact, the call you had is incorrect because you're passing a char to a function expecting a char *. In the next iteration of stringToUpper, it attempts to dereference that invalid pointer which causes the crash.
You should be incrementing sName (which points to the current character), not *sName.
The corrected version:
while(*sName != '\0')
{
*sName=toupper(*sName);
++sName;
}
Related
This question already has answers here:
Why is the gets function so dangerous that it should not be used?
(13 answers)
Closed 2 years ago.
I am learning C and decided to play around with the code, but not being able to find out where is the vulnerabity in this code.
I have pasted my code here:
#include <stdio.h>
char getPasswd() {
int trigger = 'K';
char data[100];
gets(data);
return (char) trigger;
}
void login() {
printf("inside!\n");
exit(0);
}
void main() {
printf("enter ");
if (getdata() == 'G') {
login();
} else {
printf("wrong.\n");
exit(1);
}
}
If any more info is required please let me know. What I think is vulnerbility is in gets() line 6 since its not safe to use that. I am new so not sure any help is appreciated.
The vulnerability is indeed in the gets function. you do:
char passwd[100];
gets(passwd);
The buffer is in this case 100 bytes long, so if someone inputs a string longer then 100 characters, your passwd buffer will overflow and possibly overwrite some important data that is stored after that password. to stop this from happening, you could use (fgets(buffer, sizeof(buffer), stdin);
So your piece of code would change into:
char passwd[100];
fgets(passwd, 100, stdin);
gets() has no bounds checking. So technically you can enter a password larger than 100 bytes and corrupt the stack.
For example on my machine, I could enter a password of
TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
(108 characters), overwriting the (possibly) adjacent variable trigger from 'F' to 'T', thereby making your code print the "logged in" message.
But this heavily depends on which platform you are running and your compiler, etc..
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a little problem with a C-programm, I wrote. It should be like "you go in a room.. is there a wall? no? then move on.. is there a wall? yes? then turn around" and so on. I am stucked, I go in the room and turn around but do not know how to go further.
#include <stdio.h>
void main()
{
char answer[2];
answer[0] = "Y";
answer[1] = "N";
do
{
printf("Move!\n");
printf("Is there a wall?\n");
scanf("%s",answer);
}
while (answer[0] != 'Y' );
printf("Turn around!");
}
I read about loops and ifs, but my head do not make klick.
Thanks for reading,
hjerteblod
Assuming you want to never exit the game. If so, try this code -
#include <stdio.h>
int main()
{
char answer;
while(1){
printf("Move!\n");
printf("Is there a wall?\n");
scanf(" %c", &answer);
if (answer == 'Y'){
printf("Turn around!\n");
}
}
return 0;
}
"Y" is a string with two characters, answer[0] is a character, you cannot assign a string to a character. So you can change this code like this answer[0] = 'Y'.
By the way, you are better to return an int value in the function main.
include <stdio.h>
int main(){
// your code here
return 0;
}
"N" is a string literal, which evaluates to a pointer to the first element of the string literal "Y" in memory. If you try to assign it to answer[0] you invoke undefined behavior, since you assign a address value to char objects.
The same goes for answer[1] = "N";.
Both assignments, answer[0] = "Y"; and answer[1] = "N"; should have give you a warning, like this from GCC:
warning: assignment to 'char' from 'char *' makes integer from pointer without a cast
Never ignore compiler warnings.
You don't need an array at all, use a single char for answer.
You need an infinite loop for always going further or turning back from a wall, here implemented by while (1).
Note that this is an unfinished algorithm. In a real production program you need a condition to break out of the loop. But just for the sake of your issue, here is want I think you need:
#include <stdio.h>
int main (void)
{
char answer;
while (1)
{
printf("Move!\n");
printf("Is there a wall?\n");
if ( scanf(" %c", &answer ) != 1 )
{
fputs("Error at input!", stderr);
return 1;
}
if ( answer == 'Y' )
{
printf("Turn around!\n");
}
}
}
Side Notes:
Always check the return value of input functions such as scanf() if an error occurred.
void main() is not standard compliant. Use a return type of int and declare the parameter list of type void instead of to leave it empty.
I recommend you to read a good C starting book, f.e. Modern C by Jens Gustedt or The C Programming Language Second Edition by the inventors of C.
For more information about undefined behavior, take a look at this SO question:
Undefined, unspecified and implementation-defined behavior
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm using the strcmp() fucntions to test how it works.
Ok,there is strcmp(string1,string2) that says us is ti string1 greater or smaller than string2 .
Here is my code to test this function:
#include<stdio.h>
#include<string.h>
char string1[20];
char string2[20];
int main()
{
int test;
printf("Enter 'string1'\n");
scanf("%s",&string1);
printf("Enter 'string2'\n");
scanf("%s",&string2);
test=strcmp(string1,string2);
if(test>0)
printf("String 'string1' is greater than 'string2'\n");
else if(test<0)
printf("String 'string1' is less than 'string2'\n");
else if(test==0)
printf("\n String 'string1'is equal to 'string2'");
printf("\n The value of 'test' is :%d",test);
return 0;
}
the test variable is always 1 and 'string1' is always greater than 'string2' .
pls help
strcmp is unlikely the problem. Here are a few things you can do to troubleshoot the problem.
Make sure to prevent overflow when using scanf.
Make sure that the calls to scanf are successful.
Add a line of code to print what was read so you know the values being passed to strcmp.
You don't need to use &string1 to read a string. Use just string1. Same with string2.
printf("Enter 'string1'\n");
// Read at most 19 characters from the stream, leaving space
// for the null terminator.
if ( scanf("%19s", string1) != 1 )
{
// Problem reading into string1.
printf("Unable to read string1\n");
}
printf("Enter 'string2'\n");
if ( scanf("%19s", string2) != 1 )
{
// Problem reading into string2.
printf("Unable to read string2\n");
}
printf("Input strings...\nstring1: \"%s\", string2: \"%s\"\n", string1, string2);
You should write like this, because the problem is in the scanf:
printf("Enter 'string1'\n");
scanf("%s",string1);
printf("Enter 'string2'\n");
scanf("%s",string2);
Don't use the & when you try read a string/pointer.
E.g:
char *str;
scanf("%s", str);
You can use the fread(string1, 20, stdin) to previne the string overflow
You can try the code here
The problem in your code is that while receiving string from the user , you are storing the string using scanf("%s",&string1) , You need to understand that &string1 and string1 both gives the same address,but they both are very much different.When you increment &string1 ,it points to 80 bytes further from the base address because on incrementing a pointer it points to the same location of its type ,&string1 means base address of whole array while string1 means address of the first element,so when you increment it ,it points to 4 bytes further from the base address.So when you give an address to scanf to store a string ,be careful what type of address you are giving otherwise it may give you some undefined behaviour.In your program just in place of &string1 use string1 in scanf to receive string, the remaining program is correct.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am using gcc 4.9.2-10 deb8u1 compiler to compile
Here is my code
#include <stdio.h>
int main(){
char *s;
char sa[10] , sb[10];
scanf("%s", sa);
printf("line\n");
scanf("%s", sb);
printf("%s %s", sa, sb);
}
Above code is no any problem if char is under the space provided
However
scanf("%s", s);
printf("line\n");
scanf("%s", sa);
printf("%s %s", s, sa);
Input:
$:
Hu
Result:
line
(null) Hu
Someone could told me what happen about second code wrong .?
I cannot figure out why i cannt input second one .. Thx a lot .!
In you code
char *s;
char sa[10] , sb[10];
you can't do much with s.
scanf("%s", sa);
is ok, provided the input fits. You can jump through a few hoops, reading the inputs in chunks in a loop if it might be longer (see here)
However, in you "However" section of the question you try
scanf("%s", s);
Since s doesn't point to memory - you'd need to have allocated some - you have undefined behaviour, so anything could happen.
I cannot figure out why i cannt input second one ? because s is not initialize and not having any valid address & doing scanf() on that results in undefined behaviour.
First allocate the memory and then scan the user input.
int main() {
char *s; /* its un initialized */
s = malloc(size); /* this you need to do ? specify the size value */
fgets(s,size,stdin);/* its advisable as its not having overflow problem */
printf("%s\n",s);
/* once job is done , free it by calling free(s) */
free(s);
return 0;
}
Use fgets() instead of scanf() to scan the user input for the reason listed in comments.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Was talking to a colleague today on one-spot errors - I.e. errors (or at least patterns that should ring an alarm bell) in code that a decent programmer should be able to spot at a single glance like
x = malloc (strlen(y));
while (!feof (f)) {
...
}
char *f(){
char x[100];
...
return x;
}
Who has similar snippets of such patterns? I would suggest anyone who has been on SO for a while will have his personal favourites of those
char *buf;
scanf("%s", buf);
This is wrong, because no memory has been allocated for buf.
char buf[100];
scanf("%s", &buf);
This is wrong, because scanf expects a char *, not a char (*)[n].
char c;
while ((c = getchar()) != EOF)
putchar(c);
This is wrong, because EOF does not fit in the range of a char. Use int instead.
fflush(stdin);
fflush is undefined for input streams, like stdin, albeit this is implemented as an extension in some compilers, like Microsoft C.
#define IN 0;
Do not put semicolons at the end of a #define.
blk = realloc(blk, n);
If realloc fails, any contents in blk will be lost, because realloc will return NULL. To solve the problem, copy the return value into a temporary and only if the temporary is not NULL, copy to the final destination.