在C代码中调用两个函数会停止程序

时间:2016-01-29 18:36:48

标签: c string pointers char

我正在开发一个MongoDB解释器,在我的工作中,我编写了一些函数来从char数组中提取一些字符串。 第一个函数在两个分隔符之间获取一个字符串。

char* getContent(char* doc,char firstsep,char secsep){
int whichsep = 0, i = 0 , j = 0;
char* d;
d = (char*) malloc(sizeof(char));

while(whichsep != 2){
    if(whichsep == 1) {
        d[j]=doc[i];
        j++;
    }
    if(doc[i]==firstsep) whichsep = 1;
    if(doc[i]==secsep) whichsep = 2;
    i++;
}
d[j-1]='\0';
return d;
};

第二个函数检查字符串是否包含" _id"

    int containsID(char* doc){

int i=0,j=0,c=0;
int * colonpos = (int*)malloc(sizeof(int));
while(doc[i]!= '\0') {
    if(doc[i]==':' ){
        colonpos[j]=i;
        j++;
    }
    i++;
}
colonpos[j] = 0;
char*  id = (char*)malloc(sizeof(char));
int containsID = 0;
i=0;j=0;
while( colonpos[i] != 0 && containsID !=1 ){

    j=colonpos[i]-1;
    while(doc[j]!=','&& doc[j]!='{'){
        id[c]=doc[j];
        j--;
        c++;
    }
    id[c]='\0';
    id = flipArray(id);
    if(strcmp(id,"_id")==0)
    containsID = 1 ;
    c=0;
    i++;
}
return containsID ;

};

这是主要功能

int main()
{
char* doc = "db.__fdlkdf.insert({p:231,g:{a:21},tomato:[21,25]})";
if(containsID(doc)==0) puts("no  id ");
else puts("has id");

char* e1 = (char*)malloc(100*sizeof(char));
strcpy(e1,getContent(doc,'(',')'));
printf("%s\n",e1);


return 0 ;
}

当我运行该文件时,它会显示:

enter image description here

但是当我单独调用这些函数时程序可以运行!

如果你们能帮帮我的话,我很高兴地感激不尽!

2 个答案:

答案 0 :(得分:2)

您的程序调用未定义的行为。不要指望任何好事 在声明中

d[j]=doc[i];

对于i > 0,您正在访问数组越界。 d只是一个char的数组,在第二个函数中类似colonposid

答案 1 :(得分:0)

这是一个有效的代码,

char* getContent(char* doc,char firstsep,char secsep){
  int len;
  char *doc2, *buff;
  // try to find first delimiter
  while( *doc != firstsep){
    if(!*doc)
      return NULL;
    doc++;
  }

  doc++; // firstsep found skip in one char next

  doc2=doc;

  // try to find second  delimiter
  while(*doc2 != secsep){
    if(! doc2)
      return NULL;
        doc2++;
  }

  // its all OK, copy it;
  len = doc2 - doc;
  buff=malloc(len *sizeof(char));

  if(buff){
    memcpy(buff,doc,len);
    buff[len]=0;
  }

  return buff;

};