【发布时间】:2021-07-22 04:39:27
【问题描述】:
我正在编写一个程序,我需要在其中获取第二个命令行参数的值,以便稍后确定要使用的算法。
命令行参数:$ ./project2 FIRSTFIT 268435456 testfile.txt
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
//~~~~~~~~~~~~~~~~ Main
int main(int argc, char *argv[])
{
/*
Reading in the parameters from command line
argv[0] = the program
argv[1] = the type of memory allocation algorithm to use
argv[2] = N = total memory allocation
argv[3] = script file (.txt)
*/
char* memAlgoType = (char*)argv[1];
int totalMemAlloc = atoi(argv[2]);
FILE* file;
file = fopen(argv[3], "r");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ First fit
if(strcmp(memAlgoType, "FIRSTFIT") == 0)
{
//code for first fit algorithm here
}
}
当我这样做时,我收到分段错误(核心转储)错误,并且在我的 XCode IDE 上,我在使用 strcmp() 时收到 EXC_BAD_ACCESS 错误
我已尝试将我的代码修改为 char memAlgoType = (char)argv[1][0]; 以仅比较第一个字符
我试过strcpy(memAlgoType, argv[1]),也试过memcpy()方法。所有这些都给了我分段错误。
我不知道从这里做什么......
感谢您的帮助!
【问题讨论】:
-
您应该在尝试使用
argv之前检查argc。 -
如果您实际上没有传递命令行参数,就会发生您遇到的错误。
-
您的程序对我来说运行良好(当我添加缺少的右括号时)。这是您正在测试的完整程序吗?如果没有,错误可能在您遗漏的部分;在这种情况下,minimal reproducible example 是必不可少的。
-
当你直接从 XCode IDE 运行时,你可能没有任何命令行参数
标签: c segmentation-fault command-line-arguments