2015-03-03 77 views
-2

我真的很难过。当我运行我的程序时,我不断收到分段错误错误。我一直在玩弄它一段时间,我怀疑错误可能在于我的内存分配或释放。请帮助:(我不知道我在做什么错误谢谢使用标记方法C Seg错误:可能的malloc错误?

CODE:!

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] != '\0'){ 
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] = '\0'; 
194 
195 return arr; 
196 } 

TEST:

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: Pass\n"); 
148 else 
149  printf("Test 1: Fail\n"); 
150 if (compare(test[1], "it")) 
151  printf("Test 2: Pass\n"); 
152 else 
153  printf("Test 2: Fail\n"); 
154 if (compare(test[4], "space")) 
155  printf("Test 3: Pass\n"); 
156 else 
157  printf("Test 3: Fail\n"); 

free(testFour); 
+0

供参考:http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Barmar 2015-03-03 00:41:23

+0

你是否启用了mem转储?你可以使用gdb来读取它们。另外,如果它是内存泄漏valgrind是你的朋友 – JNYRanger 2015-03-03 00:41:34

回答

2

您正在使用合格numTokens地址不初始化它,然后使用该地址处的值

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

因为它没有初始化v alue可能是任何事情,所以应该发生意想不到的事情,例如分段故障。

另外

+0

看起来'numTokens'是'tokenize'应该根据输入字符串计算的东西。 – Barmar 2015-03-03 00:43:29

+0

好吧,所以我调整了一些东西,结果我的numTokens没有被计算出来。一旦我在malloc之前将计算插入到该方法中,我的seg错误就消失了。多谢你们 – 2015-03-03 00:52:27