获取预定义字符串的长度与从输入中获取一个
taking length of predefined string vs getting one from input
我似乎无法理解为什么这两种情况的表现不同:
const char* TEXT = "hello world!";
int length = (int) strlen(TEXT);
char* array[length];
没关系,但是这个:
char* text;
scanf("%[^\n]s", text);
// input "hello world!" and press enter
int length = (int) strlen(text);
char* array[length];
以分段错误结束
我错过了什么?
对于 scanf
调用,text
参数,您没有分配任何内存。您也不会将变量初始化为一个值。这会导致 scanf
写入随机内存,从而导致分段错误。
要解决此问题,您需要分配一个合理大小的缓冲区:
char* text = malloc(1024);
1024
是您期望输入数据的最大大小。然而,这仍然使代码容易受到缓冲区溢出的影响。为防止缓冲区溢出,您可以通知 scanf
text
已达到一定大小;寻找答案 here
如果您不想自己分配内存,scanf
可以为您完成:
Note that the POSIX 2008 (2013) version of the
scanf()
family of functions supports a format modifier m
(an
assignment-allocation character) for string inputs (%s
, %c
, %[
).
Instead of taking a char *
argument, it takes a char **
argument,
and it allocates the necessary space for the value it reads:
char *buffer = 0;
if (sscanf(data, "%ms", &buffer) == 1)
{
printf("String is: <<%s>>\n", buffer);
free(buffer);
}
If the sscanf()
function fails to satisfy all the conversion
specifications, then all the memory it allocated for %ms
-like
conversions is freed before the function returns.
我似乎无法理解为什么这两种情况的表现不同:
const char* TEXT = "hello world!";
int length = (int) strlen(TEXT);
char* array[length];
没关系,但是这个:
char* text;
scanf("%[^\n]s", text);
// input "hello world!" and press enter
int length = (int) strlen(text);
char* array[length];
以分段错误结束
我错过了什么?
对于 scanf
调用,text
参数,您没有分配任何内存。您也不会将变量初始化为一个值。这会导致 scanf
写入随机内存,从而导致分段错误。
要解决此问题,您需要分配一个合理大小的缓冲区:
char* text = malloc(1024);
1024
是您期望输入数据的最大大小。然而,这仍然使代码容易受到缓冲区溢出的影响。为防止缓冲区溢出,您可以通知 scanf
text
已达到一定大小;寻找答案 here
如果您不想自己分配内存,scanf
可以为您完成:
Note that the POSIX 2008 (2013) version of the
scanf()
family of functions supports a format modifierm
(an assignment-allocation character) for string inputs (%s
,%c
,%[
). Instead of taking achar *
argument, it takes achar **
argument, and it allocates the necessary space for the value it reads:char *buffer = 0; if (sscanf(data, "%ms", &buffer) == 1) { printf("String is: <<%s>>\n", buffer); free(buffer); }
If the
sscanf()
function fails to satisfy all the conversion specifications, then all the memory it allocated for%ms
-like conversions is freed before the function returns.