pythoniku
pythoniku

Reputation: 3662

malloc and heap in c

consider the code below:

#include "list.h"
struct List
{
   int size;
   int* data;
};
List *list_create()
{
   List *list;
   printf("%d %d",sizeof(list),sizeof(List));
   list = malloc(sizeof(list));
   assert(list != NULL);
   if (list != NULL) {
      list->size = 0;
   }
   return list;
}

The number printed out is "4 8", i assume this is the 4 bytes taken by "int size" in List object?and the size of "int* data" is 0 cause nothing has assigned to data? the size of int pointer is also 4 bytes so the type List take 8 bytes in total? or there are some thing else going on? Can some one help me understand all this in detail?

then the malloc() get 4 bytes from the heap and assign the address to the pointer list? later in main if i do "list->data[i]=1;" this will give me a run time error why? Is it because I cant change contents in the heap? but if i do "list->size++" this would work, isn't the whole list object is in the heap?

really need some help here

Thanks in advance.

Upvotes: 2

Views: 826

Answers (2)

Salvatore Previti
Salvatore Previti

Reputation: 9050

sizeof(List*) is the size of a pointer to a List struct.

sizeof(list) in your case, since variable list is of type List* is the same as sizeof(List*).

sizeof(List) instead is the size of the struct List, it contains two 32 bit variables (I assume you are using a 32 bit compiler obviously), an integer and a pointer and your compiler decided that the right size for your struct is 8 bytes.

Pointers to types are usually 4 byte in 32 bit compilers and 8 bytes in 64 bit compilers.

As a side note, reading your code however i read you never initialize list->data, you should initialize it to something somewhere i guess.

This is C++ however, you should write

typedef struct { ... } List; // This is C.

Sizeof operator is evaluated at compile time, not at runtime, it gives only information of the size of a type. You cannot, for example, know how much elements are in a dynamic array with sizeof, if you were trying to accomplish this, sizeof(pointer) will give you the size in byte of the pointer type.

As something to read about what is a pointer and what is an array i would suggest you to read http://www.lysator.liu.se/c/c-faq/c-2.html or http://pw1.netcom.com/~tjensen/ptr/pointers.htm

Upvotes: 5

chacham15
chacham15

Reputation: 14251

Technically your code has an error in it.

The code should read: sizeof(struct List) or have typedef struct List List; somewhere.

But yes, sizeof(list) is the size of the variable list. Since list is a pointer it is equivalent to sizeof(void*) which on your system/compiler is 4.

sizeof(struct List) is the size of the struct which is sizeof(int)+sizeof(int*)+any alignment issues. The alignment thing is often forgotten but is very important as it can change the size of the struct in unexpected ways.

Upvotes: 2

Related Questions