简体   繁体   English

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

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

The Backstory: 背景:

I created a function to destroy an array of strings in c. 我创建了一个函数来销毁c中的字符串数组。

I pass the pointer to the array into this function, first freeing the individual strings, then the array itself. 我将指向数组的指针传递给此函数,首先释放各个字符串,然后释放数组本身。

When I run the program I get the following error: 当我运行程序时,出现以下错误:

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

I'm almost certain im passing in the right pointer. 我几乎可以确定即时消息传递了正确的指针。 What am I missing? 我想念什么?

The Code: 编码:

#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--;
  }
}

Thanks in advance! 提前致谢!

strtok function does not allocate memory. strtok函数不分配内存。 It returns pointer to char inside passed string. 它在传递的字符串中返回指向char的指针。 So you should not release memory for it. 因此,您不应为此释放内存。 This part of code: 这部分代码:

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

must be omitted 必须省略

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

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