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";
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";
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Mind = Blown (in regard to how the = is not treated the same way in those two scenarios)
ASKER
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
So as Sara mentioned, the below would be the correct way:
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' ?
char str[1000];
strcpy(str, "abc");
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.
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>>