#include <stdlib.h>
    #include <string.h>
     int main(int argc, char *argv[]) {
     char *first, *second, *third;
     first = malloc(888);
     second = malloc(22);
     third = malloc(22);
     strcpy(first, argv[1]);
     strcpy(second, argv[2]);
     free(first);
     free(second);
     free(third);
     return(0);
     }

Like I said before, I need help learning C and trying to figure out my errors. With this code, am I vulnerable in terms of memory allocation? Could an attacker take advantage? If yes, please help me with your recommendations and guides

Thanks

I'd say yes you are.

You don't know the size of string you are copying into your buffers, so could cause overflow.

Maybe strncpy would be better, I believe only amount of chars specified are copied, but you have to terminate it yourself.

Edited 2 Years Ago by Suzie999

Your code performs precisely zero length, existence, or success checks, so it's absolutely vulnerable to malicious use. It's also brittle in the face of legitimate use. Let's add a few checks to make it better:

#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {
    char *first, *second;

    first = malloc(888);
    second = malloc(22);

    if (first != NULL && argc > 1) {
        first[0] = '\0';
        strncat(first, argv[1], 887);
    }

    if (second != NULL && argv > 2) {
        second[0] = '\0';
        strncat(second, argv[2], 21);
    }

    free(first);
    free(second);

    return(0);
}

Of course, in practice the arguments may be required and/or related to each other, in which case the tests would be different. Right now they're entirely independent.

Hi,
You should check length of string by using strlen(argv[i]), then calculate size of first, second, and so on, that is N = (strlen(argv[i]) + 1). Okay, now you can allocate room for the string:

first = (char *)malloc(sizeof(char) * N);

Check the allocating is okay then copy string from argv[i] to first, second, and so on.
Hope this helps!

Thanks guys, though am trying to put things together. Got some more help from a friend and he talked about "unlink technique" Does that show up any where on the code?

Got some more help from a friend and he talked about "unlink technique"

Sounds like non-standard terminology. Did he go into detail about what that means?

This article has been dead for over six months. Start a new discussion instead.