输入 returns 正确的字符串但不 运行 函数
Input returns the correct string but doesn't run the function
我有以下代码:
bool get_command(char *cmd){
char *cm = (char*)malloc(strlen(cmd));
strcpy(cm,cmd);
const char *tok = strtok(cm," ");
if(!tok)
return false;
if(!strcmp(tok,"MULTIPLY"))
{
printf("WORKING!\n");
return true
}
....
int main(void){
while(1){
char *input = NULL;
char buf[MAX_LINE_LENGTH] = {0};
int read;
size_t len;
read = getline(&input, &len, stdin);
if (-1 != read){
printf("Input: %s\n", input);
sprintf(buf, "%s", input);
get_command(input);
} else {
printf("No line read\n");
}
free(input);
}
return 0;
}
当我 运行 代码并输入 MULTIPLY
时 returns
input: MULTIPLY
TOKEN: MULTIPLY
然而,这并没有打印出 WORKING
。谁能解释为什么这不能按预期工作?
在您的代码中,您需要更改
char *cm = (char*)malloc(strlen(cmd));
到
char *cm = malloc(strlen(cmd) + 1);
有 space 用于终止空字符。
strlen()
不计算终止 null,如果您在复制期间不分配内存来保存 null,您将面临内存溢出导致 undefined behavior.
根据 strcpy()
的 man page
char *strcpy(char *dest, const char *src);
The strcpy()
function copies the string pointed to by src
, including the terminating null byte ('[=17=]'
), to the buffer pointed to by dest
. The strings may not overlap, and the destination string dest
must be large enough to receive the copy.
也就是说,根据 getline()
的 man page
getline()
reads an entire line from stream, storing the address of the buffer containing the text into *lineptr
. The buffer is null-terminated and includes the newline character, if one was found.
由于您的定界符字符串不包含 \n
,令牌将包含 \n
。为避免,请执行以下任一操作
- 在分隔符字符串中包含
\n
- 使用
strncmp()
进行比较。
- 输入后删除
\n
。
此外,请 do no cast malloc()
的 return 值。
我有以下代码:
bool get_command(char *cmd){
char *cm = (char*)malloc(strlen(cmd));
strcpy(cm,cmd);
const char *tok = strtok(cm," ");
if(!tok)
return false;
if(!strcmp(tok,"MULTIPLY"))
{
printf("WORKING!\n");
return true
}
....
int main(void){
while(1){
char *input = NULL;
char buf[MAX_LINE_LENGTH] = {0};
int read;
size_t len;
read = getline(&input, &len, stdin);
if (-1 != read){
printf("Input: %s\n", input);
sprintf(buf, "%s", input);
get_command(input);
} else {
printf("No line read\n");
}
free(input);
}
return 0;
}
当我 运行 代码并输入 MULTIPLY
时 returns
input: MULTIPLY
TOKEN: MULTIPLY
然而,这并没有打印出 WORKING
。谁能解释为什么这不能按预期工作?
在您的代码中,您需要更改
char *cm = (char*)malloc(strlen(cmd));
到
char *cm = malloc(strlen(cmd) + 1);
有 space 用于终止空字符。
strlen()
不计算终止 null,如果您在复制期间不分配内存来保存 null,您将面临内存溢出导致 undefined behavior.
根据 strcpy()
char *strcpy(char *dest, const char *src);
The
strcpy()
function copies the string pointed to bysrc
, including the terminating null byte ('[=17=]'
), to the buffer pointed to bydest
. The strings may not overlap, and the destination stringdest
must be large enough to receive the copy.
也就是说,根据 getline()
getline()
reads an entire line from stream, storing the address of the buffer containing the text into*lineptr
. The buffer is null-terminated and includes the newline character, if one was found.
由于您的定界符字符串不包含 \n
,令牌将包含 \n
。为避免,请执行以下任一操作
- 在分隔符字符串中包含
\n
- 使用
strncmp()
进行比较。 - 输入后删除
\n
。
此外,请 do no cast malloc()
的 return 值。