Chris Gong Chris Gong - 1 month ago 7
C Question

Unable to free char-pointer element of a struct when the string reaches a certain length

Below I have a struct defined to contain one element of type

char*


struct TokenizerT_ {
char * name;
};

typedef struct TokenizerT_ TokenizerT;


And when I create an instance of the struct
TokenizerT
, I allocate the memory needed for the struct and its element,

TokenizerT *TKCreate(char * ts) {
TokenizerT *t= (TokenizerT *) malloc(sizeof(TokenizerT));
t->name= (char *) malloc(sizeof(ts));
strcpy(t->name,ts);
return t;
}


In the main function, I take in a string through the command line using
scanf
and print out certain things that could perhaps help solve the issue,

int main(int argc, char **argv) {
TokenizerT *token;
char input[50];
scanf("%s",input);
char *pin = input;
token = TKCreate(pin);

printf("The address of the tokenizer is %p\n", token);
printf("The length of the name is %lu\n", strlen(token->name));
printf("The address of the name is %p\n", token->name);
printf("The size of the TokenizerT structure is %lu\n", sizeof(TokenizerT));
printf("The name starting from character 27 is %s\n", token->name + 26);
pin=token->name;
printf("The whole name is %s\n",pin);

TKDestroy(token);

return 0;
}


The problem is being caused by my TKDestroy method in which I free the only member of the struct but I'm not sure why,

void TKDestroy( TokenizerT * tk ) {
free(tk->name);
//free(tk);
}


When running the program and inputting a string of length 26 or smaller, the program runs fine with no error.

enter image description here

But once I input a string longer than 26 characters, this happens

enter image description here
enter image description here

I know the error is being caused when I free the struct's char-pointer because I commented out the line where I freed the entire struct instance. Also, changing the size of the char array,
input
, seemed to have had no effect on the output. The error seems to only be occurring when I try to free a struct's char pointer that points to a string that has a length longer than 26. I've been told that it usually has to do with trying to free memory that's not allocated or is forbidden by access. However I am still able to access the memory addresses of the characters after the 26th character. Why is this the case?

Answer

You may try to remove the memory allocation for

       t->name 

and change it to

     t->name=ts;

Also, you have to remove the command

    strcpy(t->name,ts);

because that job is performed by the previous command. Then it should give you no errors. As far as the TKDestroy(..) you can include the command you commented that is the

    free(tk); 

Hope these help.