【发布时间】:2014-03-06 21:36:15
【问题描述】:
我编写了一个程序,它将一个字符串分解为由空格分隔的标记,然后将每个单独的字符串复制到一个字符串数组中。
程序运行良好,直到它到达 for 循环,并且在成功将第一个字符串添加到数组并打印后,程序崩溃。我调试了一下,发现
args[i] = malloc((strlen(comm_str) + 1) * sizeof(char));
返回SEGFAULT 然后第二次执行循环。调用堆栈也打印出以下内容:
地址:75F943F9,函数:strlen(),文件:C:\Windows\syswow64\msvcrt.dll。`
我尝试自己更正程序,但没有结果。起初我以为循环试图访问超出绑定区域,但我认为我已经正确地 malloc'd 一切。
#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);
}
【问题讨论】:
-
"返回 SEGFAULT 然后 [...]" - 再来一次?
-
您可能忘记正确分配内存。 args[0...num-1] 也应该是 malloc 的。 “然后返回 SEGFAULT...”听起来不对。
-
我认为
then是when的拼写错误 -
@vpit3833 他在 malloc 时遇到了段错误。
-
否,然后 i=0,循环执行没有问题并打印出“cmdline”,但之后 (i=1) at 'args[i] = malloc((strlen(comm_str) + 1 ) * sizeof(char));'发生 SEGFAULT。
标签: c arrays string segmentation-fault