473,396 Members | 1,827 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

How to find the size of dynamically allocated struct-type variable?

Hi,

I could not find any answer to this simple question of mine.

Suppose I have to write a program, the main parts of it are as follows:

#include <blahblah.h>

struct
{
double *my_dynamic_variable1;
int **my_dynamic_variable2;
char ***my_dynamic_variable3;
} gv;

main()
{
FILE *fbinary;
fbinary = fopen("test.bnr","wb");

ALLOCATE memory for gv.my_dynamic_vairable1, 2 and 3;

fwrite(gv,sizeof(gv),1,fbinary);
....
}

The problem is that, since gv is dynamically allocated at run-time, and
gv contains various variable types, how can I correctly find the actual
size of the variable gv, in order to write it corerctly to the file?
The same question raised when reading gv from a binary file. Is there
any alternative (but elegant way) of finding the size of gv, without
using sizeof?

Nov 15 '05 #1
5 5568
Le 21-10-2005, nm****@gmail.com <nm****@gmail.com> a écrit*:
I could not find any answer to this simple question of mine.
Did you really have read a C book ?
Suppose I have to write a program, the main parts of it are as follows:

#include <blahblah.h>

struct
{
double *my_dynamic_variable1;
int **my_dynamic_variable2;
char ***my_dynamic_variable3;
} gv;

main()
{
FILE *fbinary;
fbinary = fopen("test.bnr","wb");

ALLOCATE memory for gv.my_dynamic_vairable1, 2 and 3;

fwrite(gv,sizeof(gv),1,fbinary);
....
}

The problem is that, since gv is dynamically allocated at run-time, and
gv contains various variable types, how can I correctly find the actual
size of the variable gv, in order to write it corerctly to the file?


Did you mean 'the size of variable gv' (known at compile time:
sizoeof(gv)), or 'the total size of allocated fields of gv' ?

Because there is no way to known the size dynamicaly allocated
except to keep it from the allocation instruction.
Marc Boyer
Nov 15 '05 #2
nm****@gmail.com a écrit :
The problem is that, since gv is dynamically allocated at run-time, and
gv contains various variable types, how can I correctly find the actual
size of the variable gv, in order to write it corerctly to the file?


It's your job to record the size of the allocated blocs. Here is a
common approach for a flexible array :

struct array_of_int
{
int *a;
size_t n;
};

and here is the generic version :

struct array
{
/* address of the first element */
void *arr;

/* size of an element */
size_t size;

/* number of elements */
size_t number;
};

of course, you provide the create/delete/access functions that hide the
gory details...

--
C is a sharp tool
Nov 15 '05 #3
nm****@gmail.com a écrit :
The problem is that, since gv is dynamically allocated at run-time, and
gv contains various variable types, how can I correctly find the actual
size of the variable gv, in order to write it corerctly to the file?


It's your job to record the size of the allocated blocks. Here is a
common approach for a flexible array :

struct array_of_int
{
int *a;
size_t n;
};

and here is the generic version :

struct array
{
/* address of the first element */
void *arr;

/* size of an element */
size_t size;

/* number of elements */
size_t number;
};

of course, you provide the create/delete/access functions that hide the
gory details...

--
C is a sharp tool
Nov 15 '05 #4

nm****@gmail.com wrote:
Hi,

I could not find any answer to this simple question of mine.

Suppose I have to write a program, the main parts of it are as follows:

#include <blahblah.h>

struct
{
double *my_dynamic_variable1;
int **my_dynamic_variable2;
char ***my_dynamic_variable3;
} gv;

main()
{
FILE *fbinary;
fbinary = fopen("test.bnr","wb");

ALLOCATE memory for gv.my_dynamic_vairable1, 2 and 3;

fwrite(gv,sizeof(gv),1,fbinary);
....
}

The problem is that, since gv is dynamically allocated at run-time, and
gv contains various variable types, how can I correctly find the actual
size of the variable gv, in order to write it corerctly to the file?
The same question raised when reading gv from a binary file. Is there
any alternative (but elegant way) of finding the size of gv, without
using sizeof?


The thing is, the size of "gv" itself will not change as you allocate
memory: it will always be sized to hold three pointer values. The size
of the memory that the pointers point to is what's variable, and that's
something you have to keep track of manually as you allocate the
memory.

Secondly, the fwrite() call above won't do what you think it will. It
will write the contents of the struct, which is three pointer values.
It will not write the contents of what the pointers point to. Instead,
you will need to call fwrite separately on each member:

fwrite(gv.my_dynamic_variable1, sizeof *(gv.my_dynamic_variable1),
num_dv1_elements, binary);

/**
* Assumes memory for my_dynamic_variable2 is contiguous
*/
fwrite(gv.my_dynamic_variable2, sizeof **(gv.my_dynamic_variable2),
num_dv2_elements, binary);

etc.

I recommend you store the sizes as part of the struct, and create a
wrapper to abstract out the fwrite operations, like so:

struct gv {
double *my_dynamic_variable1;
size_t dv1size;

int **my_dynamic_variable2;
size_t dv2size_d0;
size_t dv2size_d1;

char ***my_dynamic_variable3;
size_t dv3size_d0;
size_t dv3size_d1;
size_t dv3size_d2;
} gv;

....

void write_gv(FILE *stream, struct gv gv)
{
/**
* Write the size of each array, followed by the array contents
*/
fwrite((void*) &gv.dv1size, sizeof gv.dv1size, 1, stream);
fwrite((void*) gv.my_dynamic_variable1, sizeof
*(gv.my_dynamic_variable1), gv.dv1size, stream);

fwrite((void*) &gv.dv2size_d0, sizeof gv.dv2size_d0, 1, stream);
fwrite((void*) &gv.dv2size_d1, sizeof gv.dv2size_d1, 1, stream);

/**
* If the array contents are contiguous, you can write the whole
* thing out in one call as below. If not, you'll have to write
* each row out separately in a loop.
*/
fwrite((void*) gv.my_dynamic_variable2, sizeof
*(gv.my_dynamic_variable2), gv.dv2size_d0 * gv.dv2size_d1, stream);

/**
* etc.
*/
}

DISCLAIMER: the above has not been tested, and I don't do binary I/O as
a rule, so there may be errors in the above. It should give you an
idea of what you need to do, however.

Nov 15 '05 #5
nm****@gmail.com writes:
I could not find any answer to this simple question of mine.

Suppose I have to write a program, the main parts of it are as follows:

#include <blahblah.h>

struct
{
double *my_dynamic_variable1;
int **my_dynamic_variable2;
char ***my_dynamic_variable3;
} gv;

main()
{
FILE *fbinary;
fbinary = fopen("test.bnr","wb");

ALLOCATE memory for gv.my_dynamic_vairable1, 2 and 3;

fwrite(gv,sizeof(gv),1,fbinary);
....
}

The problem is that, since gv is dynamically allocated at run-time, and
gv contains various variable types, how can I correctly find the actual
size of the variable gv, in order to write it corerctly to the file?
The same question raised when reading gv from a binary file. Is there
any alternative (but elegant way) of finding the size of gv, without
using sizeof?


Presumably the line "ALLOCATE memory for ..." involves calls to
malloc(). The size of gv itself is fixed, and can be computed with
"sizeof gv", so presumably you want to know the size of the memory
you've allocated.

It seems obvious that, given

char *ptr;
ptr = malloc(1000); /* assume malloc() succeeds */

there should be some way to retrieve the allocated size, 1000, from
ptr. After all, the implementation has to know how much memory was
allocated so it can deallocate it when you call free(ptr).

But the C standard provides no such function.

Why not? For one thing, the actual allocated size might be more than
you asked for; for example, malloc(1000) might allocate a block of
1024 bytes. The implementation isn't required to keep track of both
1000 (the amount requested) and 1024 (the amount actually allocated).

Now if the standard had defined such a function, all the implementers
would provide it and I don't think anyone would complain about the
minor burden. But it doesn't, so if you want to know how many bytes
you allocated, you're on your own. You know how many bytes you
requested, so you just need to remember it.

Your fwrite() call writes the contents of the variable gv itself to
your file. That means you'll get 3 pointer values written to the
file, which is not a useful thing to do (the pointer values are
meaningless outside the current execution of your program).
Presumably you want to write the data that gv points to. Since gv
contains a pointer-to-double, a pointer-to-pointer-to-int, and a
pointer-to-pointer-to-pointer-to-char, we have no way of knowing what
kind of data structure is out there (arrays, linked lists, whatever).
You'll need to figure out just what data you want to write to the
file, and how you want to represent it so that it can be read back in
later. Anything involving pointers will have to be translated to some
other form.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Tony Johansson | last post by:
Hello Experts!! When you instansiate varaibles(object) you can do so in four different scops which are. Within a block which is called Local or block scope . Within a function which is called...
2
by: songfire | last post by:
Hi everybody! Just wondering if it is possible to point to variables in the heap. For example, is this okay? int * ptr_to_DAIA; // pointer to dynamically allocated integer array ptr_to_DAIA =...
48
by: Michel Rouzic | last post by:
I know it must sound like a newbie question, but I never really had to bother with that before, and I didn't even find an answer in the c.l.c FAQ I'd like to know what's the really proper way...
5
by: tricard | last post by:
Good day all, I have created a two dimensional array (matrix for my purposes) whose size is dynamically allocated. (i.e. rowSize and colSize are both taken as input, then malloc() is used to...
6
by: bwaichu | last post by:
Is my understanding of the allocation of these correct? I used fixed sized allocations for the example below, so I realize there is some optimization that can be done to those. I would like to...
4
by: wyrmmage | last post by:
hello :) I need to make a dynamically allocated array of pointers, using a .hpp and .cpp file; how do I accomplish this? I think I know how to make an array of pointers, and I know how to make a...
3
by: Jinkuzo | last post by:
Have been working on this project for a week, unfortunately missed the lesson on it and have been struggling to figure it out. These are the instructions and the point at which I'm up to. ...
43
by: Frodo Baggins | last post by:
Hi all, We are using strcpy to copy strings in our app. This gave us problems when the destination buffer is not large enough. As a workaround, we wanted to replace calls to strcpy with strncpy....
8
Hackles
by: Hackles | last post by:
Hello, Is it possible to retrieve the size of allocated memory from a pointer (more specifically, a pointer returned my malloc/realloc). This question may have already been asked countless times....
7
by: Tapas Bose | last post by:
Hello. I want to find size of a dynamically allocated array in my following code : #include <iostream> #include <cstdlib> using namespace std; int main() {
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.