繁体   English   中英

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

[英]c - Function to free an array of strings

背景:

我创建了一个函数来销毁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函数不分配内存。 它在传递的字符串中返回指向char的指针。 因此,您不应为此释放内存。 这部分代码:

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

必须省略

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM