问题
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;
}
回答1:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int makearg(const char s[], char ***args);
int main(void){
char **args = NULL;
const char *str = "ls is a -l file";
int argc = makearg(str, &args);
printf("argc : %d\n", argc);
int i;
for(i = 0; i < argc; i++){
puts(args[i]);
free(args[i]);
}
free(args);
return 0;
}
int wordCount(const char *s){
char prev = ' ';
int wc = 0;
while(*s){
if(isspace(prev) && !isspace(*s)){
++wc;
}
prev = *s++;
}
return wc;
}
int makearg(const char s[], char ***args /*out*/){
int argc = wordCount(s);
int len;
if(argc == 0){
*args = NULL;
return 0;
}
*args = malloc(argc * sizeof(char*));
argc = 0;
while(1){
while(isspace(*s))
++s;
if(EOF==sscanf(s, "%*s%n", &len))
break;
(*args)[argc] = malloc(len + 1);
strncpy((*args)[argc], s, len);
(*args)[argc++][len] = '\0';
s += len;
}
return argc;
}
回答2:
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.
来源:https://stackoverflow.com/questions/25798468/segmentation-fault-when-parsing-c-string-into-pointer-array