【发布时间】:2014-04-24 00:51:43
【问题描述】:
我真的被一段非常简单的代码困住了。
该程序采用./a.out -t=1,32,45,2 之类的参数,并在标准输出中打印逗号数量。但是有时执行会正常工作,并且经常会引发分段错误。
我在substr_cnt这行函数中发现了这个问题(我还在下面的代码中放置了相应的注释):
target_counting = (char *)malloc(sizeof(char)*(strlen(target)));
实际上 malloc 返回 NULL。如果我将sizeof(char) 更改为sizeof(char *),所有的工作都会像魅力一样开始,但我不明白为什么会这样。此外,在 main 函数中,我也使用 malloc,甚至使用同一行
arg_parameter = (char *) malloc(sizeof(char)*(strlen(argv[1] - 3)));
一切正常。
#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;
}
【问题讨论】:
-
您应该知道 strncpy 不保证包含空终止符。这就是您的程序崩溃的部分原因。
-
我不认为你想要这个:
strlen(argv[1] - 3)inmallocinmain()。应该是strlen(argv[1]) - 3。
标签: c segmentation-fault malloc