简体   繁体   中英

free an array of strings gives SIGABRT

I am trying to free an array of strings in this manner:

unsigned char **strings = words.strings;
for (int i = 0; i < noOfWords; ++i) {
    free(strings + i);
}

but I get a SIGABRT (error code 134) with the message:

free(): invalid pointer: 0x0000000001c69018

However if I do this:

unsigned char **strings = words.strings;
for (int i = 0; i < noOfWords; ++i) {
    free(strings[i]);
}

then everything works just fine.

Can someone point me the difference? Shouldn't these two forms be equivalent?

In your first snippet, you missed to dereference the pointer.

free(strings + i);

should be

free(*(strings + i));

In case of free(strings + i); you are trying to increment the pointer-to-pointer, ie, the string itself. Actually, what you want is to free each valid element pointed by string which are given by string[i] . So, string[i] is basically de-referencing the pointer string to get all the elements pointed by it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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