令牌方法的C Seg错误:可能是malloc错误



我真的被难住了。当我运行程序时,我不断地遇到分段错误。我已经玩了一段时间了,我怀疑错误可能在于我的内存分配或释放。请帮忙:(我不知道我做错了什么。谢谢!

代码:

163 //Arguments: s1, delimter                                                                          
164 //Returns a pointer to a char array containing entries for each token in s1.  Think of this        
165 //as a 2-D array.  Each row contains a char* (token).  This function creates a NEW char**          
166 //variable and NEW char* variables for each token.  Your method should be memory efficient.        
167 //In other words, the space created for each token should be an exact fit for the space            
168 //that token needs.  If a token is five characters, allocate 5 bytes (plus null terminator).       
169 //The function also writes the number of tokens into the numTokens variable.      
170 char** tokenize(const char *s, char delimiter, int *numTokens){
171   //set variables                                                                                  
172   int i,j,a;
173     //alloacte space                                                                               
174   char **arr = (char **)malloc((*numTokens) * sizeof(char *));
175   for (i=0; i<(*numTokens); i++){
176     arr[i] = (char *)malloc(50 * sizeof(char));
177   }
178 
179   //while loop to search commence second search                                                    
180   //fill new 2d array                                                                              
181   while(s[a] != ''){
182     if(s[a] == delimiter){
183       j++;
184       i = 0;
185     }else{
186       arr[i][j] = s[a];
187       i++;
188     }
189     a++;
190   }// end while                                                                                    
191 
192   //to end arr                                                                                     
193   arr[i][j] = '';
194 
195   return arr;
196 }

测试:

137   char **test;
138   char *testFour;
139   int numTokens, *token;
140   testFour = (char *)calloc(50, sizeof(char));
141   sprintf(testFour, "check it with a space");
142   token = &numTokens;
143 
144   test = tokenize(testFour, ' ', token);
145 
146   if (compare(test[0], "check"))
147     printf("Test 1: Passn");
148   else
149     printf("Test 1: Failn");
150   if (compare(test[1], "it"))
151     printf("Test 2: Passn");
152   else
153     printf("Test 2: Failn");
154   if (compare(test[4], "space"))
155     printf("Test 3: Passn");
156   else
157     printf("Test 3: Failn");
free(testFour);

您使用的是在不初始化numTokens的情况下传递地址,然后在中使用该地址的值

char **arr = (char **)malloc((*numTokens) * sizeof(char *));

由于它没有初始化,该值可能是任何值,因此应该发生意外的事情,例如分段错误。

还有

  • 不投射malloc()的结果
  • 定义为CCD_ 3

相关内容

  • 没有找到相关文章

最新更新