Hi everyone, I'm having a problem. I'm trying to get three differents *char in order to check if they math between themselves ( actually just to check two of them).
But when I call the function to get the second and the third password (the *char's are passwords, but I write a new code in order to simplify the problem) the new reads overwrite the previous one.
Here is the code:
#include <cstdlib>
#include <iostream>
#include <conio.h>
#include <windows.h>
usingnamespace std;
HANDLE consol;
char *getPass(void)
{
COORD pos;
consol = GetStdHandle(STD_OUTPUT_HANDLE);
cout<<"[";
CONSOLE_SCREEN_BUFFER_INFO consolInfo;
GetConsoleScreenBufferInfo(consol, &consolInfo);
pos.X = consolInfo.dwCursorPosition.X;
pos.Y = consolInfo.dwCursorPosition.Y;
cout<<"__________]";
SetConsoleCursorPosition(consol, pos);
char letra,pass[10];
int i=0;
do
{
letra = getch();
if (letra!=8 && letra!=13 && i<10)
{
pass[i]=letra;
cout<<"*";
i++;
}
elseif (letra==8 && i>0)
{
cout<<"\b"<<"_"<<"\b";
i--;
}
}
while (letra!=13);
pass[i]='\0';
staticchar fpass[10];
strcpy(fpass,pass);
return fpass;
}
int main (void)
{
char *word1,*word2;
word1 = (char*) malloc(300);
word2 = (char*) malloc(300);
cout<<"Write First Word: ";
word1=getPass();
cout<<"\nWrite Second Word: ";
word2=getPass();
cout<<"\nThe words are: "<<word1<<" and "<<word2;
getch();
}
For example, if the input is: MyPass1, and then I write MyPass2, the variable word1 will be overwritten by the new input leaving the variables with the same string.
So I wanted to know why these happens. I'm really new at c++ so this may be a really foolish matter that I just can't realized the reason.
By the way, I apologize for my bad english, since it's not my first language.
Thank You!! I didn't know that the pointer fpass remains with the same memory location.
Knowing what the problem was...couldn't be possible to release the pointer after returning it?
In order to avoid overwritting the same memory location. For example, like using: