I have made a program that breaks a string into tokens separated by space and then copies each separate string into an array of strings.
Program works fine until it reaches for-loop and after successfully adding the first string into the array and printing it, program crashes. I debugged it and found that
args[i] = malloc((strlen(comm_str) + 1) * sizeof(char));
returns SEGFAULT then performing loop for the second time. Also call stack prints out the following:
Address: 75F943F9, Function: strlen(), File: C:\Windows\syswow64\msvcrt.dll.`
I tried to correct program myself, but with no result. I thought at first that loop tries to access out of bound region, but I think I have malloc'd everything correctly.
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main(){
char **args = NULL;
char input[] = "cmdline -s 20 -r -t parameter -p 20 filename";
int num = 0;
char *comm_str = strtok(input, " "); /*Tokens command line*/
while(comm_str != NULL){ /*Counts number of tokens*/
num++;
printf("%s %d\n", comm_str, strlen(comm_str));
comm_str = strtok(NULL, " ");
}
printf("\n");
args = malloc(num * sizeof(char*)); /*Allocates memory for the first string entry*/
if(!args){
return 0;
}
comm_str = strtok(input, " "); /*Starts tokening from beginning*/
for(int i = 0; i < num; i++){
args[i] = malloc((strlen(comm_str) + 1) * sizeof(char)); /*Allocates memory for strings*/
if(!args[i]){
for(int b = 0; b < i; b++){
free(args[b]);
}
free(args);
return 0;
}
strcpy(args[i], comm_str);
printf("%s\n", args[i]);
comm_str = strtok(NULL, " ");
}
printf("%d\n", num);
}
thenis a typo forwhen