Question

I want to create the program with C++ and this login on my server FTP and occurs if there is a new file in the folder of server.

My friend already created this program, it is functioning (working) and passes it to me .

Inside the program we using the library and tools of CURL for login on FTP.

On my computer this program not working using DEV C++. Then I create the new project, rewrite all code of old program, load the library of CURL and Compile.

The program get problem of executing.

Analyze the program there is an anomaly with MALLOC.

This is a code where is there a anomaly:

 char* userpwd = (char*)malloc(strlen(USERNAME)+1+strlen(PASSWORD));
 printf("\n malloc %s",userpwd);
          strcat(userpwd, (const char*)USERNAME);
          strcat(userpwd, ":");
          strcat(userpwd, (const char*)PASSWORD);
 printf("\n not %s",userpwd);

Explain how this function: First, I have to build the variable that contain "USERNAME:PASSWORD". The problem is after char* userpwd = (char*)malloc(strlen(USERNAME)+1+strlen(PASSWORD)); Because when I print the value of userpwd, I have - or other characters before the string. Then is normal the login is incorrect or denied.

This is the image: enter image description here

For function without problem, I can change the code:

char userpwd[50];
              userpwd="USERNAME";
              strcat(userpwd, ":");
              strcat(userpwd, "PASSWORD");
     printf("\n not %s",userpwd);

And this function.

But the program read the file configuration.txt for obtain the URL, USERNAME and PASSWORD. Then is convenient to use malloc but in my computer and on my sister, I have the anomaly of characters.

How can I prevent these anomalies? Why do I have these strange characters? Thanks for any help possible

P.S: I delete the string USERNAME and PASSWORD with colour white for protect my account.

Was it helpful?

Solution

You forgot to add 1 for the terminating zero.
You also forgot to zero-terminate the string before you strcat onto it.
That leads to undefined behaviour.

char* userpwd = (char*)malloc(strlen(USERNAME) + 1 + strlen(PASSWORD) + 1);
userpwd[0] = 0;

Or (better) use idiomatic C++:

std::string USERNAME;
std::string PASSWORD;
// Load username and password...

std::string pass = USERNAME + ":" + PASSWORD;

and pass pass.c_str() to the login function

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top