How do I properly work with Strings in C?

262 Views Asked by At

The likes of Java, Python, and others have ruined me. I'm trying to automate an FTP client by responding to server codes:

For example:

// I know this is ugly, please bear with me

char username[25];
strcat(username, USER); //"USER "
strcat(username, usr); // "foo"
strcat(username, "\n"); // = "USER foo\n"

char password[25];
strcat(password, PASS); //"PASS "
strcat(password, pswd); //"bar"
strcat(password, "\n"); // = "PASS bar\n"


//read/write loop

while (1) { 

    char* responsePtr;
    serverCode = readSocket(sockfd, mybuffer);

    if (serverCode == 221) 
                    break;

    if (serverCode == 220)
        responsePtr = &username;

    if (serverCode == 331)
        responsePtr = &password;

    writeSocket(sockfd, responsePtr);

}

When I try this, it works for USER, but I get some mangled text for PASS:

C->S: USER anonymous
S->C: 331 Please specify the password.
C->S: (??_?PASS random

Can anyone wiser and more experienced than myself give me some C string pointers? Clearly this isn't working out for me.

4

There are 4 best solutions below

5
On BEST ANSWER

You need to initialize your strings before you concatenate to them. Arrays are not initialized by default.

char username[25] = "";
char password[25] = "";

For what it's worth, you can use sprintf to create the strings more easily:

sprintf(username, "USER %s\n", usr);
sprintf(password, "PASS %s\n", pswd);

Hopefully you also realize that using fixed size buffers is a recipe for buffer overflow bugs. For security you should make sure to guard against them. It's annoying, but that's C for you:

if (snprintf(username, 25, "USER %s\n", usr)  >= 25 ||
    snprintf(password, 25, "PASS %s\n", pswd) >= 25)
{
    fprintf(stderr, "buffer overflow\n");
    exit(EXIT_FAILURE);
}
3
On

Try adding "\n\0" instead of just "\n" to the username and password arrays.

1
On

You shouldn't strcat an uninitialized array. Try:

char *password[25] = "";
password = strcat(PASS);

for the fist one.

Also, instead of strcat() you should use strncat() to avoid overflows.


I think it's easier to do:

int len = snprintf(password, 25, "%s %s\n", PASS, pswd);
if (len > 25) {
    // oops! password is too long dude :-(
}

See here for some examples.

0
On

A few rules that help.

  • Remember to initialize and null terminate your strings.
  • Use the library functions.
  • Check the string lengths and/or use n (size limited) functions when working with external data.
  • Don't forget the terminator when sizing buffers.