malloc(u); 2

Posted by kAworu Wed, 06 May 2009 10:23:00 GMT

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

struct foo {
    int garbage[42];
    char *name;
};

int
main(int argc, char *argv[])
{
    struct foo *f;
    size_t s;

    if (argc < 2)
        return (EXIT_FAILURE);

    s = (strlen(argv[1]) + 1) * sizeof(char);
    f = malloc(sizeof(struct foo) + s);
    if (f == NULL)
        return (EXIT_FAILURE);
    f->name = &f[1];
    strlcpy(f->name, argv[1], s);

    (void)printf("What you say?\n%s\n", f->name);

    free(f);
    return (EXIT_SUCCESS);
}