c - 使用 strcpy() 时出现分段错误
问题描述
我们添加了打印语句来检查分段错误发生的位置。它在 strcpy(command, token); 处失败;我们如何将该部分存储到命令中?还有一种方法可以检查令牌末尾的空字符吗?strtok() 使用时末尾是否有空字符?
int main(int argc, char **argv)
{
char *command, *flag, *pathname, *linkname;
struct stat st = {0};
char cmd[200];
char *token; //Pointer
int counter = 1; //Counter variable
FILE *fp;
char mode2[] = "0750"; //To set the permission of a file/path
long j;
char mode[] = "0640"; //To set the permission of a file/path
long i;
fgets(cmd, 200, stdin);
printf("print for cmd: %s\n", cmd);
//User input is tokenized to determine the proper commands are entered and executed
token = strtok(cmd, " "); //Input is tokenized by white spaces.
printf("token: %s\n", token);
strcpy(command, token);
printf("print for command: %s\n", command);
if(token == NULL)
{
printf("Error with command input.\n");
exit(EXIT_FAILURE);
}
解决方案
在使用 strcpy() 为其赋值之前,您需要初始化 *command 变量。如果您尝试将值分配给 NULL 指针,则会发生分段错误。
正确使用 strcpy() 应该是这样的:
char *str = malloc(3 * sizeof(char));
char sentence[3] = "Hi\0";
strcpy(str, sentence);
printf("%s\n", str);
推荐阅读
- powerbi - 在 power bi 过滤器上上传值列表文本文件
- c++ - 如何将这两个功能组合到一个实现中?
- pandas - 我想验证日期格式是 YYYY-MM-DD,如果用户输入任何其他格式,它应该显示为错误(熊猫)
- r - R:data.frame 将不接受行输入并将我的变量更改为 N/A 值
- c++ - C++ 无法转换 std::vector
到字符串或字符数组 - c++ - VSCode - C++ 未定义的对 'CLASS::FUNCTION' 的引用
- r - R:错误:美学必须是长度 1 或与数据相同:x
- testcontainers - 容器不以 GenericContainer 开头
- android - Flutter 检查是否在另一个应用程序上执行了操作
- webrtc - 实时广播摄像机的最佳方式