灾难性的糟糕:
int main(void){
char *s;
int ln;
puts("Enter String");
// scanf("%s", s);
gets(s);
ln = strlen(s); // remove this line to end seg fault
char *dyn_s = (char*) malloc (strlen(s)+1); //strlen(s) is used here as well but doesn't change outcome
dyn_s = s;
dyn_s[strlen(s)] = '\0';
puts(dyn_s);
return 0;
}
更好的:
#include <stdio.h>
#define BUF_SIZE 80
int
main(int argc, char *argv[])
{
char s[BUF_SIZE];
int ln;
puts("Enter String");
// scanf("%s", s);
gets(s);
ln = strlen(s); // remove this line to end seg fault
char *dyn_s = (char*) malloc (strlen(s)+1); //strlen(s) is used here as well but doesn't change outcome
dyn_s = s;
dyn_s[strlen(s)] = '\0';
puts(dyn_s);
return 0;
}
最好的:
#include <stdio.h>
#define BUF_SIZE 80
int
main(int argc, char *argv[])
{
char s[BUF_SIZE];
int ln;
puts("Enter String");
fgets(s, BUF_SIZE, stdin); // Use fgets (our "cin"): NEVER "gets()"
int ln = strlen(s);
char *dyn_s = (char*) malloc (ln+1);
strcpy (dyn_s, s);
puts(dyn_s);
return 0;
}