我正在编写一个函数来将命令行解析为char * arguments数组到另一个程序,但后来我遇到了分配和/或读取结果缓冲区的问题。我被困在那里大约2天以及之后的1000多次谷歌搜索,我自己也无法解决这个问题。
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h> //for malloc, realloc
char** parse_cmdline(const char* cmdline) {
int wrdc = 0; //word count
int wrd_len = 0; //current word length
char** args = NULL; //result buffer, filled with arguments
int i; //counter of characters read from cmdline
for(i = 0; ; ++i){
if(cmdline[i] == '\n') {
if(wrd_len > 0) {
++wrdc;
args = realloc(args, wrdc * sizeof(char*));
memcpy((void*)&args[wrdc - 1], (void*) &cmdline[i - wrd_len], wrd_len);
printf("EOL found\n");
wrd_len = 0;
}
break;
}
else if(cmdline[i] == ' ') {
if(wrd_len > 0) {
++wrdc;
args = realloc(args, wrdc * sizeof(char*));
memcpy((void*)&args[wrdc - 1], (void*) &cmdline[i - wrd_len], wrd_len);
printf("space found!\n");
wrd_len = 0;
}
}
else if(cmdline[i] > 32 && cmdline[i] < 127) {
++wrd_len;
printf("char found !\n");
}
//FOR DEBUGGING
printf("i = %d, wrdc = %d, wrd_len = %d\n", i, wrdc, wrd_len);
}
printf("%d words in command\n", wrdc);
return args;
}
int main(int argc, char* argv[]) {
char buffer[200];
while(read(STDIN_FILENO, buffer, 200) > 0) {
char** data = parse_cmdline(buffer);
printf("%s\n", data[0]);
memset(buffer, 0, 200);
free(data);
}
return 0;
}
答案 0 :(得分:1)
else if(cmdline[i] == ' ') {
if(wrd_len > 0) {
++wrdc;
args = realloc(args, wrdc * sizeof(char*));
memcpy((void*)&args[wrdc - 1], (void*) &cmdline[i - wrd_len], wrd_len);
printf("space found!\n");
wrd_len = 0;
}
}
这里存储在args[wrdc-1]
中的指针未初始化并指向某个未知的地方。你不应该memcpy()
将cmdline
改为args[wrdc-1]
。
在memcpy()
:
args[wrdc-1] = calloc(wrd_len+1, sizeof(char));
请注意+1
和calloc()
以终止NULL字符。请记得在main()
中释放它们。