Link to home
Start Free TrialLog in
Avatar of pzozulka
pzozulka

asked on

C Programming: Learning about memory

One of the biggest problems I'm having with C is the understanding of pointers and memory allocation.

Question 1:
What is the difference between:

char buffer[1000];

vs.

char *buffer;
buffer = malloc ( 1000 * sizeof(char) );

Question 2:
What is the string length of str? Anything wrong with the below?
char str[1000];
str = "abc";
Avatar of Kyle Abrahams, PMP
Kyle Abrahams, PMP
Flag of United States of America image

Malloc is used to allocate memory to the heap, and needs to be unallocated with free().  Lifetime is as long as you want it to be.

With the array, it's allocated on the stack, and memory is automatically reclaimed once you lose scope.

Some good reading on this here:
<<Link to competing site removed>>
SOLUTION
Avatar of masheik
masheik
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of pzozulka
pzozulka

ASKER

Mind = Blown (in regard to how the = is not treated the same way in those two scenarios)
char str[1000];

Please confirm if this is true: After the above command, the char array would have { '\0', '\0', '\0', ... , '\0' }.

char *str = malloc ( 1000 * sizeof(char) );
This char array would also have { '\0', '\0', '\0', ... , '\0' }. Can I call this an array?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
So as Sara mentioned, the below would be the correct way:
char str[1000];
strcpy(str, "abc"); 

Open in new window


Then please confirm if this is true: the char array would have { 'a', 'b', 'c', '\0', junk, junk, ... , junk } ? How did the '\0' get in there? Is that a feature of strcpy() -- it automatically appends '\0' ?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
In addition to what kaufmed has stated, you still have to be careful with strncpy too. True, it will limit the number of bytes/chars that it will copy (so that you are protected if the input string in NOT null-terminated). However, if while copying this limit IS reached, it will NOT append a null char itself. So due to this, you can actually create a situation where the resultant string is NOT null-terminated. Therefore, when using strncpy, you still have to manually ensure that the result is definitely null-terminated.