分段故障解析C字符串成指针数组时 [英] Segmentation fault when parsing c string into pointer array
问题描述
该函数makearg应该计数的字的数量在字符数组,也向上打破每个字到一个指针数组自己点。
分段故障似乎是与函数strncpy功能的问题。
INT makearg(char中[],CHAR ***参数);诠释主(){ 焦炭** ARGS =(字符**)(的malloc(100)); 字符*海峡=LS是一个-l文件;
INT ARGC;
ARGC = makearg(STR,&安培;参数); 的printf(%D的argc);
的printf(%C,'\\ 0'); INT I;
对于(i = 0; I< ARGC,我++){
看跌期权(参数);
的printf(%C,\\ n);
}
返回0;
}/////////////////////////////////////////INT makearg(char中[],CHAR ***参数){ INT ARGC = 0;
INT charc = 0;
INT wordstart = 0; 而(1){
如果(S [charc] =='\\ 0'){
函数strncpy(* ARGS [ARGC],S + wordstart,charc - wordstart);
ARGS [ARGC] [(charc - wordstart)+ 1] ='\\ 0'; ARGC ++;
打破;
} 如果(S [charc] ==''){
函数strncpy(* ARGS [ARGC],S + wordstart,charc - wordstart);
ARGS [ARGC] [(charc - wordstart)+ 1] ='\\ 0'; wordstart = charc + 1;
ARGC ++;
charc ++;
} 其他{
charc ++;
}
}
返回ARGC;
}
您分配指针的 ARGS
阵列空间,但你永远不为你想让你的字符串分配空间存储在其中,所以当你尝试存储在 makearg
的琴弦,你是跨preting任何随机的垃圾有一个指针,而不是要的工作。
另外,你只分配100的字节的的指针数组 - 目前还不清楚有多少
你期望的话,能够分裂,但的malloc
调用应该看起来可能更像
的char ** ARGS =的malloc(MAX_WORDS * sizeof的(字符*)); / *不需要造型* /
然后按照一个循环做MAX_WORDS多个的malloc
调用,以初始化 ARGS
与有效的指针
The function makearg is supposed to count the number of words in a char array and also break each word up into their own spot in a pointer array. Segmentation fault seems to be a problem with the strncpy function.
int makearg(char s[], char ***args);
int main(){
char **args = (char**)(malloc(100));
char *str = "ls is a -l file";
int argc;
argc = makearg(str, &args);
printf("%d", argc);
printf("%c", '\0');
int i;
for(i = 0; i < argc; i++){
puts(args);
printf("%c", '\n');
}
return 0;
}
/////////////////////////////////////////
int makearg(char s[], char ***args){
int argc = 0;
int charc = 0;
int wordstart = 0;
while(1){
if(s[charc] == '\0'){
strncpy(*args[argc], s + wordstart, charc - wordstart);
args[argc][(charc - wordstart) + 1] = '\0';
argc++;
break;
}
if(s[charc] == ' '){
strncpy(*args[argc], s + wordstart, charc - wordstart);
args[argc][(charc - wordstart) + 1] = '\0';
wordstart = charc + 1;
argc++;
charc++;
}
else{
charc++;
}
}
return argc;
}
You allocated space for the args
array of pointers, but you never allocate space for the strings you intend to store in them, so when you try to store the strings in makearg
, you are interpreting whatever random garbage is there as a pointer, and that's not going to work.
Also, you only allocate 100 bytes for the pointer array -- it's not clear how many
words you expect to be able to split, but the malloc
call should probably look more like
char **args = malloc(MAX_WORDS * sizeof(char *)); /* no cast required */
then follow that with a loop to do MAX_WORDS more malloc
calls, in order to initialize args
with valid pointers.
这篇关于分段故障解析C字符串成指针数组时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!