如果我想将字符串best school复制到内存中的新空间中,我可以使用哪些语句选项来为它保留足够的空间
#define _GNU_SOURCE // asprintf
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main() {
char s[] = "best school";
// no free(); stack allocation
char *s2 = strdup(s);
free(s2);
// sizeof works here because s is an array; see later
// strlen() which works both both array and pointers.
char *s3 = malloc(sizeof(s));
memcpy(s3, s, sizeof(s));
free(s3);
// stack allocated (i.e. < 8k including other
// parameters and fails badly.
char *s4;
asprintf(&s4, "%s", s);
// no free(); stack allocation
char *s5 = calloc(sizeof(s), 1);
strcat(s5, s);
free(s5);
char *s6 = calloc(strlen(s) + 1, 1);
strncat(s6, s, strlen(s));
free(s6);
char *s7 = malloc(sizeof(s));
strncpy(s7, s, sizeof(s) - 1);
free(s7);
// strlen(s) is determined at run-time hence s8 is a vla
char s8[strlen(s) + 1];
memcpy(s8, s);
// no free(); stack allocation
}
,在Linux上,你需要设置宏_GNU_SOURCE,通常你用-D_GNU_SOURCE而不是在源代码本身。