0

I'm trying to create an array of words. What's the difference between creating array like this:

char* myWords[10];

and

char* myWords = malloc(10*sizeof(char *))

I'm assuming that since the first one happens automatically, that the memory is reaped at the end of the function execution. Is that correct?

1
  • You could allocate off the stack using | char * mywords = _alloca(10*sizeof(char *)); | , and the memory would automatically be freed at function exit. Commented Apr 1, 2015 at 21:02

3 Answers 3

2

These are very different types.

The first creates an array of pointers in the usual (automatic) way. The 10 pointers are valid until the function end. They don't point to anything valid with this alone, but can each point to a separate string that can be accessed from each element of the array.

The second allocates a chunk of memory to a single pointer to a character. Thus you would expect it to point to a string (up to 40 or 80 bytes typically). The memory is valid until you free it, but the pointer is automatic just like the first. (Note that an array of character pointers decays to char ** and not char *.)

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

Comments

0

Yeah, the first one is actually added onto the stack, therefor destroyed once the actual function is returned, and the second one is added onto the heap.

Comments

0

The malloc data is allocated to the heap and the other one to the stack. Malloc puts your data on the heap, which you have to control yourself. After you are done with the data, you should free the data (check the man pages on malloc) so that you don't have memory leaks.

Maybe this website provides you with more insight: http://gribblelab.org/CBootcamp/7_Memory_Stack_vs_Heap.html

1 Comment

Bear in mind that anything to do with heaps and stacks has nothing to do with C itself, it's just usually how a platform implements C.

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.