我真的很難過。當我運行我的程序時,我不斷收到分段錯誤錯誤。我一直在玩弄它一段時間,我懷疑錯誤可能在於我的內存分配或釋放。請幫助:(我不知道我在做什麼錯誤謝謝使用標記方法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);
供參考:http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Barmar 2015-03-03 00:41:23
你是否啓用了mem轉儲?你可以使用gdb來讀取它們。另外,如果它是內存泄漏valgrind是你的朋友 – JNYRanger 2015-03-03 00:41:34