I am really stuck with one very simple piece of code.
This program takes argument like ./a.out -t=1,32,45,2
and prints quantity of commas in stdout. But from time to time execution works correctly and and more often throws segmentation fault.
I figured out that problem in this line of function substr_cnt
(I also placed corresponding commentaries in code below):
target_counting = (char *)malloc(sizeof(char)*(strlen(target)));
In fact malloc returns NULL. If I change sizeof(char)
by sizeof(char *)
all starts work like a charm but I can't understand why is that. Furthermore in main function I also use malloc, and even with the same line
arg_parameter = (char *) malloc(sizeof(char)*(strlen(argv[1] - 3)));
all works just fine.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define strindex(target, source) ((size_t) strstr(target, source) - (size_t) target)
int substr_cnt( char *target, char *source ) {
int i=0;
int cnt=0;
char *target_counting;
//this is NOT working
target_counting = (char *)malloc(sizeof(char)*(strlen(target)));
//this is working
//target_counting = (char *)malloc(sizeof(char *)*(strlen(target)));
if (target_counting == NULL) {
printf("malloc failed\n");
return -1;
}
strcpy(target_counting, target);
while ((i=strindex(target_counting, source)) > 0) {
strncpy(target_counting, target_counting + i + 1, strlen(target_counting));
cnt++;
}
free(target_counting);
return cnt;
}
int main( int argc, char *argv[] )
{
int i;
int default_behavior = 0;
int arg_parametr_cnt;
char *arg_parameter;
if (argc == 1) {
default_behavior = 1;
} else if (argv[1][0] == '-' && argv[1][1] == 't' && argv[1][2] == '=') {
//this is working
arg_parameter = (char *) malloc(sizeof(char)*(strlen(argv[1] - 3)));
strncpy(arg_parameter, argv[1]+3, strlen(argv[1]));
printf("%s\n", arg_parameter);
arg_parametr_cnt = substr_cnt(arg_parameter, ",");
printf("commas: %d\n", arg_parametr_cnt);
}
else {
printf("wrong command line");
return 1;
}
return 0;
}