1,105,556 Community Members

Byte amounts of variabless

Member Avatar
DmytriE
Newbie Poster
16 posts since Oct 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Hello everybody,

I have never done anything with dynamic memory allocation and was trying to allocate enough memory to hold four elements of an array. Each of these elements will hold another array that will hold the actual data.

My questions is how can I check the size of a variable to make sure there is enough memory allocated. I am not talking about using an if statement. I would like the actual value of how much memory the variable uses.

//Declaration of variable
int *matrices = NULL;			//Pointer to the set of matrix registers

matrices = (int*) malloc(4 * sizeof(int));
printf("%d\n", *matrices);

I was thinking that if I use printf statement and the dereferencing operator with the variable then I could see the value 16. But I continue to see the number 4. This occurs if I change sizeof(int) to char, float, double, etc. Any ideas would be helpful.

Thanks!

Member Avatar
gerard4143
Nearly a Posting Maven
2,385 posts since Jan 2008
Reputation Points: 371 [?]
Q&As Helped to Solve: 409 [?]
Skill Endorsements: 0 [?]
 
1
 

If the memory manager can fulfill the malloc request it will return a memory pointer to the allocated memory...if it fails it returns NULL.

If malloc returns a pointer other than NULL then you have your requested memory.

Member Avatar
sergent
Posting Pro
593 posts since Apr 2011
Reputation Points: 52 [?]
Q&As Helped to Solve: 26 [?]
Skill Endorsements: 0 [?]
 
0
 

The OS will not allocate memory, if it can only allocate a portion of the memory you requested. So if matrices is not a NULL pointer after malloc() then you have your 4 ints.

Member Avatar
DmytriE
Newbie Poster
16 posts since Oct 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Thanks!

Question Answered as of 2 Years Ago by gerard4143 and sergent
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: