我試圖將argv複製到char數組,通過一些在線解決方案,但最終得到了分段錯誤。以下是我使用的代碼:將argv複製到char數組時出錯
void main (int argc,const char *argv[])
{
char *arr;
arr = (char *) malloc(strlen(argv[1])+1);
strcpy(arr,argv[1]);
}
請幫助確定我做錯了什麼。
我試圖將argv複製到char數組,通過一些在線解決方案,但最終得到了分段錯誤。以下是我使用的代碼:將argv複製到char數組時出錯
void main (int argc,const char *argv[])
{
char *arr;
arr = (char *) malloc(strlen(argv[1])+1);
strcpy(arr,argv[1]);
}
請幫助確定我做錯了什麼。
似乎argv [1]等於NULL或甚至不存在(C標準允許argc可能等於0)。
添加下面的檢查
char *arr;
if (argc > 1)
{
arr = (char *) malloc(strlen(argv[1])+1);
strcpy(arr,argv[1]);
}
else
{
// print some error message
}
一些額外的信息[這裏](http://stackoverflow.com/q/5796103/2173917) – 2014-10-31 08:05:42
@Sourav Ghosh我不明白你爲什麼低估了我的答案。 – 2014-10-31 08:08:36
我剛剛添加了一些更多信息。看到我以前的評論。和urs不一樣嗎?爲什麼我會倒下呢? – 2014-10-31 08:13:04
請大家幫忙鑑定一下我做錯了。
好吧,先生。您正在詢問argv [1],但您不確定它是否存在。在其邊界外訪問數組具有未定義的行爲。您應經常檢查,如果參數的數量是你所期望的,以避免發生不可預料的行爲:
if (argc < 2)
{
// error, cannot copy argv[1] because it doesn't exist. Explain this to user
}
// now OK..., also we postponed allocation of arr pointer
char *arr = malloc(strlen(argv[1]) + 1);
//^^^^
// no need to cast return value of malloc in C
strcpy(arr, argv[1]);
當使用命令行輸入,我們應該處理數量的參數。
你可以嘗試這樣的事情..
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main (int argc, const char *argv[])
{
if(argc==2)//change condition based on your requirements
{
char *arr;
arr = (char *) malloc(strlen(argv[1])+1);
strcpy(arr,argv[1]);
printf("string is %s\n",arr);
}
else
{
printf("check your command line input (only 2 parameters)\n");
}
}
OUTPUT:
$ ./a.out
check your command line input (only 2 parameters)
$ ./a.out hello
string is hello
$ ./a.out hi hello
check your command line input (only 2 parameters)
$
運行程序時你指定哪些參數?您應該在分配,複製之前檢查'argc> 1'。 – 2014-10-31 08:01:21
什麼是'argv [1]'? 'strlen(NULL)'會導致UB和段錯誤。請參閱[this](http://stackoverflow.com/q/5796103/2173917) – 2014-10-31 08:02:18
並且您至少向程序傳遞一個參數?請告訴我們您如何調用該程序以及您傳遞給它的參數。 – 2014-10-31 08:04:10