0

I was wondering where a struct would be allocated in memory if I have something like this.

typedef struct {
    int c;
}  A;

A * a = (A)* malloc(sizeof(A));
a -> c = 2;

C would be allocated in the heap area, is that right? Moreover, if I free the memory with

free(a);

What happens to the memory area occupied by C?

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115

5 Answers5

2
A * a = (A)* malloc(sizeof(A));

This line is incorrect, if you want to make an explicit cast, the syntax is (A*), not (A)*.

Anyway, yes, malloc allocates memory on the heap (in general and on non exotic system). What happens after depends on the OS and the implementation of the libc you use. Most often however, the memory freed is kept in a list for future use by malloc.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Taurre
  • 323
  • 1
  • 7
0

First of all you need to allocate the memory like A * a = (A*) malloc(sizeof(A));. In C when you allocate memory to a struct dynamically you need to provide total size of that struct and the return type conversion from void* to your data type. So your malloc call will allocate that much of memory and returns a void pointer to the first byte of that block of memory location.

So do not confuse that declaring variable inside a struct will be allocated from stack. Please see below:-

 int c;// c is a automatic variable and memory will be allocated from stack

 typedef struct {
     int c;// c is not a automatic variable it is simply a data member of `struct A`
 }  A;

So in the second case memory will be allocated to c only when malloc will be called at run time that is dynamically and from heap. So your free call will simply release that memory at run time.

But

typedef struct {
     int c;// c is not a automatic variable it is simply a data member of `struct A`
 }  A;

  A a;// Here 'a' is a automatic variable so 'int c' is also become automatic here 
      //and memory for the entire struct A will be allocated from stack and 
      //you no need to use `free` here

Hope this is help.

Abhijit Pritam Dutta
  • 5,521
  • 2
  • 11
  • 17
0

A * a = (A)* malloc(sizeof(A));

Where a struct would be allocated in memory?

In C, the library function malloc allocate a block of memory on the heap. The program accesses this block of memory via a pointer that malloc returns. The memory is given by the operating system. If memory is not available NULL pointer is returned.

There is no need for casting of malloc in C. Your code has a typo, if anything it should be (A *).

What happens to the memory area occupied by C?

When the memory is no longer needed, the pointer pointing to the allocated memory should be passed to free which deallocates the memory so that it can be used again. For free(NULL); the function does nothing.

C11 standard (ISO/IEC 9899:2011):

7.22.3.3 The free function

Synopsis

#include <stdlib.h>
void free(void *ptr);

Description

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

sg7
  • 6,108
  • 2
  • 32
  • 40
0

Fistly, C is a case-sensitive language.

int c is not the same as int C, so you might want to edit that in your question.

Now, lets answer your questions:

C would be allocated in the heap area, is that right?

Yes it is allocated from heap, subject to availability. If you forget to release memory that was allocated, you will exhaust it.

Lets see what C11 standard says, C11 - Section 7.22.3 states,

The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object with a fundamental alignment requirement and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated). The lifetime of an allocated object extends from the allocation until the deallocation. Each such allocation shall yield a pointer to an object disjoint from any other object. The pointer returned points to the start (lowest byte address) of the allocated space. If the space cannot be allocated, a null pointer is returned. If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.

Thats should suffice to justify why explicit typecasting in statement

A * a = (A)* malloc(sizeof(A));

is not required. So it should be

A * a = malloc(sizeof(A));

followed by test if a is NULL, if it is NULL, you shouldn't continue with further access.

What happens to the memory area occupied by C?

Again, referring to C11 standard, C11 - Section 7.22.3.3 which states,

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

a in your code is equivalent to ptr above. Once freed, you can consider that the memory is returned to heap-pool for fresh allocations. There is no memory occupied by c now, and hence an access to c results in Undefined Behavior.

Refer C11 Standard, section J.2 Undefined Behavior:

  • An object is referred to outside of its lifetime (6.2.4).
  • The value of a pointer to an object whose lifetime has ended is used (6.2.4).
WedaPashi
  • 3,561
  • 26
  • 42
0
A * a = (A)* malloc(sizeof(A));

The compiler must be giving an error on this statement and if I am guessing correctly you want to cast the malloc return with (A *) which you should not do [check this].

In C language, a structure is a user-defined datatype which allows us to combine data of different types together and size of a structure variable is

size of all member variables + size of structure padding

So, when you dynamically allocate memory of sizeof(struct name) size, a block of memory of requested size gets allocated in heap and when you pass this pointer to free(), it deallocates that whole memory block.

What happens to the memory area occupied by C?

It is deallocated.
The lifetime of a dynamically allocated object is over when it is deallocated. So, when you do free(a), the life of a and all its data members is over and it is indeterminate now.


Additional:

A point to note here about free() is that it does not change the value of the pointer (passed to it) itself, hence it still points to the same (now invalid) location.

So, when you free a dynamically allocated memory it still points to the same location which is no more valid and accessing such memory is undefined behavior. From C Standard#6.2.4p2

The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address,33) and retains its last-stored value throughout its lifetime.34) If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.

H.S.
  • 11,654
  • 2
  • 15
  • 32