Chris Gong Chris Gong - 1 year ago 63
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


struct TokenizerT_ {
char * name;

typedef struct TokenizerT_ TokenizerT;

And when I create an instance of the struct
, 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));
return t;

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

int main(int argc, char **argv) {
TokenizerT *token;
char input[50];
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);
printf("The whole name is %s\n",pin);


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 ) {

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,
, 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 Source

You may try to remove the memory allocation for


and change it to


Also, you have to remove the command


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


Hope these help.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download