0

I'm trying to figure out how to free the memory for an array of character pointers (string literals), but I can't quite get the syntax. This is how I'm declaring and initializing the arrays.

char * words[] = { "THESE", "ARE", "SOME", "WORDS" };

I've tried doing this...

free(words);

And this...

for(i = 0; i < 4; i++) {
    free(words[i]);
}

But the first one causes some sort of invalid pointer error with glibc, and the second one causes a segmentation fault.

So what's the right way to free this memory?

3
  • 5
    This is a statically initialized array. You shouldn't be freeing it anyway. Commented May 2, 2014 at 0:07
  • 1
    don't free something you didn't malloc. Commented May 2, 2014 at 0:09
  • "what's the right way"? Do nothing. It's freed automatically. Commented May 6, 2014 at 21:07

1 Answer 1

3

If you did not allocate it (e.g malloc, calloc) then you shouldn't be deallocating it either (e.g free).

Documentation will in general be very clear and explicit if you need to free a pointer returned from a function, for example strdup would be such a case.

Sign up to request clarification or add additional context in comments.

4 Comments

Ah, alright. I ask because I have some memory leaks in my program and it looked like those arrays had the right number of elements to be the culprit. Guess I get to have more fun with my vector and string libraries...
Try debugging with valgrind.
@DarinBeaudreau: Don't program by random guessing. Learn the rules of the language and follow them.
This is true in Standard C. In POSIX and compiler extensions, sometimes you find functions that return memory you must free() despite the fact that you didn't malloc it. For example, strdup and getline.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.