Solved

C Programming: Learning about memory

Posted on 2013-10-29
11
426 Views
Last Modified: 2013-10-30
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";
0
Comment
Question by:pzozulka
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
  • +3
11 Comments
 
LVL 40

Expert Comment

by:Kyle Abrahams
ID: 39610200
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>>
0
 
LVL 9

Assisted Solution

by:masheik
masheik earned 100 total points
ID: 39610760
Please refer Process Memory Layout  and storage classes in C , you may find good number of articles in google or in ee itself.

Admins , Please remove if the following link is not compliance to ee policy ,

Here is some link you can refer to
http://www.geeksforgeeks.org/memory-layout-of-c-program/
0
 
LVL 34

Assisted Solution

by:sarabande
sarabande earned 200 total points
ID: 39610973
char str[1000];
str = "abc";
the str array was located at the stack memory and not on the heap. stack memory was allocated when the process was started. heap memory is dynamic memory which was managed by heap manager.

note, the "abc" cannot assigned to str by = operator.

"abc" is a const char pointer (literal) pointing to constant memory in the stack. you cannot assign a char pointer to a char array variable. you would need to use a copy function, for example strcpy.

strcpy(str, "abc");

Open in new window


alternatively you can initialize a char array by a literal:

char str[1000] = "abc"; 

Open in new window

it looks not so much different to the first code but the = is not an assignment here but an initialization. the char array would have { 'a', 'b', 'c', '\0', <rest all '\0'> } after initialization.

Sara
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 8

Author Comment

by:pzozulka
ID: 39612063
Mind = Blown (in regard to how the = is not treated the same way in those two scenarios)
0
 
LVL 8

Author Comment

by:pzozulka
ID: 39612265
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?
0
 
LVL 75

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 200 total points
ID: 39612309
Please confirm if this is true: After the above command, the char array would have { '\0', '\0', '\0', ... , '\0' }.

No. You've only requested memory with that first declaration; you haven't initialized it. It will contain whatever junk was left in it from its last usage.***

This char array would also have { '\0', '\0', '\0', ... , '\0' }.
Same thing. malloc only request a block of memory, it does not initialize it. calloc will zero out a block of memory before it gives you back the pointer to the starting address.

See a comparison of calloc and malloc here: http://www.diffen.com/difference/Calloc_vs_Malloc

Can I call this an array?
It's memory you've requested, so it's available for your use, but as I mentioned above, there's nothing in it (since you used malloc).


*** Does not necessarily mean that the entire 1000 bytes was used previously. Only 50 bytes (or any arbitrary number less than or equal to 1000) out of that 1000 could have been allocated in a prior function call.
0
 
LVL 8

Author Comment

by:pzozulka
ID: 39612330
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' ?
0
 
LVL 75

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 200 total points
ID: 39612474
So as Sara mentioned, the below would be the correct way:
Yes.

the char array would have
Yes.

How did the '\0' get in there? Is that a feature of strcpy()
Yes and no. The \0 came from the "abc". All string literals in C are implicitly null-terminated (a feature of the compiler). strcpy will copy up to the first null character from the source string, and it will include that null character in the target string. This is why strcpy can be dangerous if you did not properly null-terminate your char* pointers:  If the source string does not properly contain a null character, then strcpy will continue copying characters--even past the "end" of the source string--until it finds a null character somewhere in memory. For this reason, it is often suggested to use strncopy instead, where they number of characters to be copied is explicitly mentioned.

You can find descriptions of each function at the following:
http://pubs.opengroup.org/onlinepubs/009695399/functions/strcpy.html
http://pubs.opengroup.org/onlinepubs/009695399/functions/strncpy.html
0
 
LVL 34

Accepted Solution

by:
sarabande earned 200 total points
ID: 39612948
in regard to how the = is not treated the same way in those two scenarios
it is confusing for a beginner, true. but also c++ or other oop language have a difference between the initial creation using = (called construction) and the assignment where you assign a right-hand term to an already existing (and sized) object.

you also should see, that the "abc" actually is not a char array but a (const) pointer to char. so, initialization of a char array has got a special in the c standard that beside of

char carr[] = { 'a', 'b', 'c', '\0' };

Open in new window

the equivalent syntax

char carr[] = "abc";

Open in new window

is valid.

if you do

carr = "abc";

Open in new window

the compiler complains because a char pointer cannot assigned to a char array but only to another char pointer. the reason for this restriction is clear if you consider that the left side has fixed size while the right operand points to a string of dynamic size.


note, as told by kaufmed, zero termination of strings is obligatory in c and all c string functions like strcpy strcat, strstr, ... would rely on it. the reason is that a char array once passed to a function turned from array type (with known size) to pointer type. the pointer points to the first array element but the size information was left. because of that, the only way to find out the length of a text stored in the char array is to search for the first binary zero character.

initialization of arrays on the stack has one more special. contrary to heap allocation with malloc, any initialization of an array would fully initialize all array elements.

char carr1[100] = { 'a', 'b' }; 
char carr2[100] = "ab";

Open in new window

both statements would initialize all elements beside the first two characters to zero.

note, in c there is no easy way (beside of calling memset) to make an array all zero later.

Sara
0
 
LVL 35

Expert Comment

by:mccarl
ID: 39612991
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.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.

733 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question