分段故障核心生成

时间:2012-08-09 18:35:44

标签: c

//我打了三次strbrk,但我需要检查是否!= NULL,怎么办呢?

if(strpbrk(posfind,"<") != NULL ){
    posfind =(char*)malloc(strlen(strpbrk(posfind,"<"))+strlen(posfind)*sizeof(char*));
    posfind =strcat(strpbrk(posfind,"<"),posfind);
}

2 个答案:

答案 0 :(得分:1)

strcat不会为您分配新的内存,您需要确保在之前有足够的空间。看起来你在strcat的调用中没有空间,因此* WHAM *。

在更新的示例中,使用一些临时变量来存储strpbrk(posfind, "<")的结果和新的malloc内存,如下所示:

char* temp = strpbrk(posfind, "<");
char* newstring = NULL;
if (temp != NULL) {
    // You had a typo with the size, and also don't forget to add a spot for the
    // terminating null character
    newstring = malloc((strlen(temp) + strlen(posfind) + 1) * sizeof(char));
    newstring = strcpy(newstring, temp);
    newstring = strcat(newstring, posfind);
    posfind = newstring;
}

当然,您还应检查所有返回值并释放我们不再使用的任何已分配内存。

答案 1 :(得分:0)

strpbrk(posfind,"<")返回一个空指针,您将传递给strcat