背景故事:
我创建了一个函数,以破坏c。
中的一系列字符串我将指针传递到该数组中的指针进入此功能,首先释放单个字符串,然后释放数组本身。
运行程序时,我会收到以下错误:
tokenDemo(4967,0x11afeb5c0) malloc: *** error for object 0x7fde73c02a05:pointer being freed was not allocated
tokenDemo(4967,0x11afeb5c0) malloc: *** set a breakpoint in malloc_error_break to debug
Abort trap: 6
我几乎可以肯定我会通过正确的指针。我想念什么?
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "token.h"
#define MAXLEN 100
int main(){
//delimiters used for tokenization
char sep[4] = {',',' ','n'};
char *strin = (char*)malloc(MAXLEN * sizeof(char));
printf("enter sentence: n");
fgets(strin, (MAXLEN + 1), stdin);
char** tokens = stringToTokens(strin, sep);
int i=0;
while(tokens[i] != NULL){
reverse(tokens[i]);
printf("%s ",tokens[i]);
i++;
}
printf("n");
printf("tokens: %dn*tokens: %sn", tokens, *tokens);
destroyTokens(tokens);
free(strin);
}
#define MAX 100 //this is the maximim number of words that can be tokenized
char **stringToTokens(char *str, char *sep){
//malloc space for the array of pointers
char **tokenArray = (char **) malloc(MAX * sizeof(char*));
char * token = strtok(str, sep);
int count = 0;
while(token!=NULL){
tokenArray[count] = token;
count ++; //tracks number of words
token = strtok(NULL, sep); //gets the next token in the string and sets it to token
}
tokenArray[count]=NULL; //adds null to last element
return tokenArray;
}
void destroyTokens(char **tokenArray){
//free the individual strings
int i=0;
while(tokenArray[i] != NULL){
free(tokenArray[i]);
i++;
}
free(tokenArray);
}
void reverse(char *s){
int length = strlen(s);
char *start, *end, temp;
start=s;
end=s;
//now actually move end to the end of the string
for(int i=0; i<length-1; i++){
end++;
}
for(int i=0; i<length/2; i++){
temp = *end;
*end = *start;
*start = temp;
start++;
end--;
}
}
预先感谢!
strtok函数不会分配内存。它将指针返回到Char中的Char。因此,您不应为此发布内存。代码的这一部分:
while(tokenArray[i] != NULL){
free(tokenArray[i]);
i++;
}
必须省略