Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strcmp with pointers not working in C

Tags:

c

pointers

strcmp

Why this code isn't working. Just trying to check if the user input is the same as a password

char *pass;

printf("Write the password: ");
scanf("%s", pass); // Because is a pointer the & is out ?


if( strcmp( pass , "acopio") == 0)
like image 907
jotape Avatar asked Nov 06 '12 14:11

jotape


People also ask

Why strcmp is unsafe?

Problem with strcmp function is that if both of the strings passed in the argument is not terminated by null-character, then comparison of characters continues till the system crashes.

How to declare strcmp function in C?

Syntax: int strcmp(const char *leftStr, const char *rightStr ); In the above prototype, function srtcmp takes two strings as parameters and returns an integer value based on the comparison of strings.

How to use strcmp with strings?

strcmp() in C/C++ This function is used to compare the string arguments. It compares strings lexicographically which means it compares both the strings character by character. It starts comparing the very first character of strings until the characters of both strings are equal or NULL character is found.


2 Answers

You've not actually allocated any space to put data. Defining a pointer just defines a variable that can hold the address of a block of data, it doesn't allocate the block.

You have a couple of options, allocate dynamic memory off the heap to write into and make the pointer point to it. Or use statically allocated memory on the stack and pass the address of it to your calls. There's little benefit to dynamic memory in this case (because it's temporary in use and small). You would have more work to do if you used dynamic memory - you have to make sure you got what you asked for when allocating it and make sure you've given it back when you're done AND make sure you don't use it after you've given it back (tricky in a big app, trust me!) It's just more work, and you don't seem to need that extra effort.

The examples below would also need significant error checking, but give you the general idea.

e.g.

char *pass = malloc (SOMESIZE);

printf("Write the password: ");
scanf("%s", pass);


if( strcmp( pass , "acopio") == 0)

or

char pass[SOMESIZE];

printf("Write the password: ");
scanf("%s", pass);


if( strcmp( pass , "acopio") == 0)
like image 138
Joe Avatar answered Sep 25 '22 14:09

Joe


pass is an unitialized pointer, and you attempt to write into it. You have to allocate enough memory to hold a string. For example, char pass[SIZE] will work better.

like image 44
md5 Avatar answered Sep 21 '22 14:09

md5