gpt4 book ai didi

c - 释放字符串数组的函数

转载 作者:行者123 更新时间:2023-11-30 18:33:46 25 4
gpt4 key购买 nike

背景故事:

我创建了一个函数来销毁 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: %d\n*tokens: %s\n", 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函数不分配内存。它返回指向传递的字符串内的字符的指针。所以你不应该为它释放内存。这部分代码:

while(tokenArray[i] != NULL){ 
free(tokenArray[i]);
i++;
}

必须省略

关于c - 释放字符串数组的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55191862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com