#include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> struct foobar { int length; char str[0]; }; void *xmalloc(size_t size) { void *p = malloc(size); assert(p != NULL); return p; } int main(int argc, char **argv) { struct foobar *p = NULL; int len = 0; if (argc > 1) { len = strlen(argv[1]); p = xmalloc(sizeof(*p) + len); p->length = len; strcpy(p->str, argv[1]); printf("%d:%s\n", p->length, p->str); free(p); } return 0; }
[masami@moon:~]% ./a.out AAAAAAAAAA 10:AAAAAAAAAA [masami@moon:~]% ./a.out AAAAAAAAAAAAAAAAAAAA 20:AAAAAAAAAAAAAAAAAAAA [masami@moon:~]% ./a.out AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 40:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA [masami@moon:~]%
一応動いているけど(*´∀`)