c - функция для освобождения массива строк - PullRequest
0 голосов
/ 16 марта 2019

Backstory:

Я создал функцию для уничтожения массива строк в 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--;
  }
}

Заранее спасибо!

1 Ответ

3 голосов
/ 16 марта 2019

функция strtok не выделяет память. Возвращает указатель на символ внутри переданной строки. Так что не стоит освобождать память для этого. Эта часть кода:

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

должен быть пропущен

...