[英]scanf seg fault in C with char* array
I'm working my way through a book on operating systems, and some of the book's sample code is giving me a runtime segmentation fault. 我正在研究一本有关操作系统的书,并且该书的一些示例代码给了我运行时分段错误。 I'm somewhat new to C from Java, and I'm hoping someone can point me in the right direction.
我对Java刚接触C有点陌生,我希望有人可以指出正确的方向。
The little program here is supposed to generate a simple shell, read a command in and fork a process to execute it. 这里的小程序应该生成一个简单的shell,读入命令并派生一个进程来执行它。 The problem is in the book's code itself, at the "scanf" function call;
问题出在本书的代码本身中,即在“ scanf”函数调用处。 when I input something at the "osh>" prompt, I get a segmentation fault.
当我在“ osh>”提示符下输入内容时,出现分段错误。
Form what I know about C, I think memory might need to be allocated for the args array, but since it's an array declared directly in the main function, I think I might not need to. 从我对C的了解来看,我认为可能需要为args数组分配内存,但是由于它是直接在main函数中声明的数组,所以我可能不需要。 I figure that if I did, it would be in the book's code.
我认为,如果这样做,它将存在于本书的代码中。
Anyway, here's the code that generates the fault: 无论如何,这是生成故障的代码:
char* args[MAX_LINE/2 + 1]; /* command line (of 80) has max of 40 arguments */
int should_run = 1;
int i, upper;
while (should_run){
printf("osh>");
fflush(stdout);
scanf("%s", args); /* THIS CAUSES SEGFAULT */
char* localArgs[3];
char* pch;
/* ... */ / * ... * /
Thanks in advance for the help. 先谢谢您的帮助。 Learning memory management in C is quite the journey.
在C语言中学习内存管理是一段漫长的旅程。
You are passing an array of pointers to scanf()
, it expects an array of char
. 您正在传递一个指向
scanf()
的指针数组,它需要一个char
数组。
An example of how to use scanf()
correctly to scan a text string would be 如何正确使用
scanf()
扫描文本字符串的示例是
char string[100];
if (scanf("%99s", string) == 1)
{
printf("scanned string: %s\n", string);
}
else
{
printf("error: unexepected error in `scanf()'.\n);
}
Read the link throughly to understand why I wrote this code like I did, if you do you will start to understand how scanf()
works, and when you do you will start writing more robust programs, and probably stop using scanf()
too. 仔细阅读链接,以了解为什么我像以前那样编写此代码,如果您这样做,您将开始了解
scanf()
工作方式,并且当您这样做时,您将开始编写更强大的程序,并且可能也停止使用scanf()
。
char* args[MAX_LINE/2 + 1];
This is creating an array of size (MAX_LINE/2+1) of char pointers. 这将创建一个大小为(MAX_LINE / 2 + 1)个char指针的数组。 If you want to use one of these char pointers as string, you must allocate them:
如果要将这些char指针之一用作字符串,则必须分配它们:
args[which_arg] = malloc(arg_max_length*sizeof(char));
And to read a text into it: 并阅读其中的文本:
scanf("%s", args[which_arg]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.