Alex Rivera | Logout

char x[256] vs. char* = malloc(256*sizeof(char));

Asked 2009-01-07T02:44:42.307
14

Someone here recently pointed out to me in a piece of code of mine I am using

char* name = malloc(256*sizeof(char));
// more code
free(name);

I was under the impression that this way of setting up an array was identical to using

char name[256];

and that both ways would require the use of free(). Am I wrong and if so could someone please explain in low level terms what the difference is?

Edit
Report

1 Answer

2

Break down your statement

char* name = malloc(256*sizeof(char)); // one statement
char *name; // Step 1 declare pointer to character
name = malloc(256*sizeof(char)); // assign address to pointer of memory from heap
name[2]; // access 3rd item in array
*(name+2); // access 3rd item in array
name++; // move name to item 1

Translation: name is now a pointer to character which is assigned the address of some memory on the heap

char name[256]; // declare an array on the stack
name++; // error name is a constant pointer
*(name+2); // access 3rd item in array
name[2]; // access 3rd item in array
char *p = name;
p[2]; // access 3rd item in array
*(p+2); // access 3rd item in array
p++; // move p to item 1
p[0]; // item 1 in array

Translation: Name is a constant pointer to a character that points to some memory on the stack

In C arrays and pointers are the same thing more or less. Arrays are constant pointers to memory. The main difference is that when you call malloc you take your memory from the heap and any memory taken from the heap must be freed from the heap. When you declare the array with a size it is assigned memory from the stack. You can't free this memory because free is made to free memory from the heap. The memory on the stack will automatically be freed when the current program unit returns. In the second example free(p) would be an error also. p is a pointer the name array on the stack. So by freeing p you are attempting to free the memory on the stack.

This is no different from:

int n = 10;
int *p = &n;

freeing p in this case would be an error because p points to n which is a variable on the stack. Therefore p holds a memory location in the stack and cannot be freed.

int *p = (int *) malloc(sizeof(int));
*p = 10;
free(p);

in this case the free is correct because p points to a memory location o

answered 2009-01-07T04:34:28.390

Your Answer