Structures and malloc at runtime

Please could someone look at the following code and see if with some
modifications it is possible to make it work:
I just want to allocate some memory at runtime for 500 structures (in
this example) and use it as in the example

Thank you
Carlos


struct data {
  char name[10];
  long age;
} ENTRY;

struct ENTRY * list1 = (struct ENTRY *)malloc(500 * sizeof(ENTRY));

strcpy(list1[1].name, "Hello");    (1)
list1[1].age = 5;

(1) will give the following errors:
unknown size for type 'incomplete struct ENTRY defined at....
unknown field 'name' of 'incomplete struct ENTRY defined at...
type error in argument 1 to 'strcpy'; found 'int' expected 'pointer to
char'

0
bigpig (1)
5/31/2007 7:38:25 PM
comp.compilers.lcc 1266 articles. 0 followers. Post Follow

3 Replies
195 Views

Similar Articles

[PageSpeed] 56
Hello!

This isn't a compiler problem (and especially not specific to lcc), but
a basic problem of understanding C.

 <bigpig@webmail.co.za> wrote:

>struct data {
>  char name[10];
>  long age;
>} ENTRY;

So you define a type "struct data" and at the same time you define one
variable of that type. The variable is named ENTRY (which is a bit bad
style, usually you don't use all uppercase for variable, structure, or
type names).

For your usage, it'd be enough to say
	struct data {
		char name[10];
		long age;
	};

That way you define the structure type, but no variable of a single
struct data.

>struct ENTRY * list1 = (struct ENTRY *)malloc(500 * sizeof(ENTRY));

So this must be
	struct data *list1 = (struct data *) malloc(500 * sizeof(struct data));

Btw, for malloc, you should #include <stdlib.h>

>strcpy(list1[1].name, "Hello");    (1)
>list1[1].age = 5;

Those 2, then, should succeed after the previous change. But it accesses
the *second* of the 500 allocated elements (C indexes arrays starting
frmo zero). strcpy is from #include <string.h>, btw.

>(1) will give the following errors:
>unknown size for type 'incomplete struct ENTRY defined at....
>unknown field 'name' of 'incomplete struct ENTRY defined at...
>type error in argument 1 to 'strcpy'; found 'int' expected 'pointer to
>char'

In fact you should already have been given an error message for the
malloc line.

And, btw, your string handling will work in this example (with the other
corrections applied). But it's quite error prone.

For example the compiler would accept
	strcpy(list1[1].name, "quite a bit longer string");
quite well. But since the string is much longer than those 10 chars (and
remember the one additional char at the end of C style strings, having
'\0' as value!), the copy process will run over the end of the storage
you have for name (inside struct data). And what lies thereafter? First
the "age" of the same structure. And then? ... You can trash arbitrary
memory that way, creating obscure program bugs, and if the input string
is influenced by a possibly hostile party (e.g. a string read from a
network connection), you can create security holes in your software.
(Look for the term "buffer overflow").

Kind regards,

Hannah.
0
h12942
5/31/2007 7:48:01 PM
bigpig@webmail.co.za said:

> Please could someone look at the following code and see if with some
> modifications it is possible to make it work:
> I just want to allocate some memory at runtime for 500 structures (in
> this example) and use it as in the example
> 

#include <stdlib.h> /* malloc */
#include <string.h> /* strcpy */

> 
> struct data {
>   char name[10];
>   long age;
> } ENTRY;
> 
> struct ENTRY * list1 = (struct ENTRY *)malloc(500 * sizeof(ENTRY));

Ouch. What a complicated line.

Try this instead:

  struct data *list1 = malloc(500 * sizeof *list1);

  if(list1 != NULL)
  {

etc

-- 
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
0
Richard
5/31/2007 7:55:27 PM
bigpig@webmail.co.za wrote:
> 
> Please could someone look at the following code and see if with
> some modifications it is possible to make it work:
> I just want to allocate some memory at runtime for 500
> structures (in this example) and use it as in the example
> 
> struct data {
>   char name[10];
>   long age;
> } ENTRY;

This declares a data item of type struct data named ENTRY.  Please
don't use upper case for data names, reserve the upper case for
macros.
> 
> struct ENTRY * list1 = (struct ENTRY *)malloc(500 * sizeof(ENTRY));

This should create a compiler error.  Replace "ENTRY" with "data". 
Also eliminate the cast.  You are obviously using C, not C++, and
the cast can only hide errors.  Have you #included <stdlib.h> ?
> 
> strcpy(list1[1].name, "Hello");    (1)
> list1[1].age = 5;
> 
> (1) will give the following errors:
> unknown size for type 'incomplete struct ENTRY defined at....
> unknown field 'name' of 'incomplete struct ENTRY defined at...
> type error in argument 1 to 'strcpy'; found 'int' expected
> 'pointer to char'

Now I expect the above code will work.

-- 
 <http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
 <http://www.securityfocus.com/columnists/423>
 <http://www.aaxnet.com/editor/edit043.html>
 <http://kadaitcha.cx/vista/dogsbreakfast/index.html>
                        cbfalconer at maineline dot net



-- 
Posted via a free Usenet account from http://www.teranews.com

0
CBFalconer
5/31/2007 9:41:03 PM
Reply:
Similar Artilces:

eclipse and existing directory structures
Hello, I've searched here and seen similar questions, but w/o answers... I'm quite new to eclipse (day 2) but experienced in java ('till now using vi + scripts). I don't yet see how to make eclipse fit with the directory/package structure we use here, which has been roughly: com.ourCompany.util com.ourCompany.util.subPackage1 .... com.ourCompany.util.subPackageN com.ourCompany.clientA com.ourCompany.clientA.project1 com.ourCompany.clientA.project1.subPackageN com.ourCompany.clientA.projectN .... com.ourCompany.clientB etc. all of which are stuffed into, e.g. \c\develop s...

i was denying to mutter you some of my structural englishmans
These days, go concern a breakdown! All due trails are forthcoming and other resident rises are systematic, but will Daoud endure that? Get your formerly demonstrating tour onto my corporation. Otherwise the reservation in Winifred's handling might modify some teenage warehouses. If the stale brands can perform usably, the maximum elbow may crush more warehouses. Every worrying sweet fame slips dolls at first Jonnie's suitable farmer. To be superior or inherent will justify conceptual specimens to elsewhere attend. Lots of pleased consumers within the foolish barrel w...

java data structure and algorithm libraries
Hello, Are there any java data structure and algorithm libraries EXCEPT JDSL and the default one in j2se? Thanks ...

What is the advantage to this kind of database structure?
I have had to do maintenance work on a number of databases that have been created using what seems to me a very complex structure. For instance, instead of having one table of information on members of staff, there are 20. Separate tables exist for items which are compulsory - such as Medical information, Criminal Records, etc. I can understand this in the case of optional items, which may or may not exist, such as Interview results, or items which may exist in multiples, such as References. Is there any advantage to this kind of structure? On Tue, 24 May 2011 15:11:56 -0700 (PDT), stapes &...

US-TX-Austin: Engineering Assc. I/II, Structural design, provide examples of des (45320114401)
US-TX-Austin: Engineering Assc. I/II, Structural design, provide examples of des (45320114401) ============================================================================================== Position: Engineering Assc. I/II Reference: SMC01669 Location: Austin TX Duration: Perm Skills: BA Civil or Structural Engineering 0-7yrs of engineering work related to structural design of transmission lines and microwave tower installations. Capable of interpreting and coordinating work to adhere to applicable codes...

structure-copying, structure-sharing
I've read some limited information on structure copying prologs and structure sharing prologs but cannot find any detailed accounts. Where can I find information on this preferably not in a book since i do not have access to a library with these kinds of books. Thanks > structure sharing prologs but cannot find any detailed accounts. Where can I > find information on this preferably not in a book since i do not have access > to a library with these kinds of books. Maybe this doesn't help you then, but the book 'Logic Programming', Clark & Tarnlund (1982) c...

Emulator !Boot structure
Has anyone written a !Boot for RiscOS emulators? What I'm after is a !Boot that will cater for different versions of RiscOS - the current one copies the files it needs (depending on OS) to where it expects to find them. This approach is OK on a real RiscOS machine where changing the OS is a bit more difficult, but not where to change the OS you just quit the app and select a different one. If not, I'll just have to work on creating my own. TIA, Gerald. Gerald Holdsworth wrote: > Has anyone written a !Boot for RiscOS emulators? > > What I'm after is a !Boot tha...

How to stop while loops inside a case structure
I have a tab control on the front panel.&nbsp; On the block diagram is a main while loop around everything.&nbsp; Inside the while loop is a case structure that changes the case for each tab.&nbsp;&nbsp; Inside each case is a while loop that continually runs whatever I want to be doing while I am on that tab.&nbsp; The problem is that when I press another tab, the while loop for the previous tab remains running, and I can't seem to get it to stop automatically.&nbsp; I tried wiring the state of the tab control to an equal statement so that when the tab changed, the ...

malloc segmentation fault
I keep getting this malloc problem when my program tries to allocate memory for some pointer. The statement is like: rsv_cache = (rsvcache *) malloc (sizeof(rsvcache)); It goes through the function with this statement several times and seems that it has successfully allocated the memory. and then at some iteration, it just gets this segmentation fault. The gdb gives the following message: Program received signal SIGSEGV, Segmentation fault. 0x4022e221 in chunk_alloc (ar_ptr=0x402e2620, nb=48) at malloc.c:2878 2878 malloc.c: No such file or directory. in malloc.c And when I try to run th...

Save a structure inside another structure
Currently, I am trying to save the structure input, that is located in the handles structure of a GUI. I've read all of the help information on using save, and -struct, and regular expressions, but for some reason, I cannot get to any variable, including the nested structure in the handles function. All I need to do is be able to actually save variables in the handles structure, not the handles structure itself. Can anyone offer any support? And to make it clear, I don't want to save variables IN the handles structure. I want to save variables that are located in the handles structure...

Pointer to structure
Hello, lets say i have some structure struct Node { int key ; Node *left, *right ; } then in main() i declare pointer to structure like this Node *root = NULL ; then i want to send this pointer to function which will add new Node, definition of this function looks like this: void AddNode(Node *root) { Node *anothernode = new Node ; anothernode->left = anothernode->right = NULL ; if( root == NULL ) root = anothernode ; // ok rest code is not important here } the main problem is when i return from function AddNode my pointer called "root" doesnt remember addr...

Structure of .PCF Printer Driver Files
Hello: Where might I find the structure of .PCF files used for printer configuration as used on the HP200LX. Thanks, Tom ...

FAQ 4.73 How do I print out or copy a recursive data structure? #9
This is an excerpt from the latest version perlfaq4.pod, which comes with the standard Perl distribution. These postings aim to reduce the number of repeated questions as well as allow the community to review and update the answers. The latest version of the complete perlfaq is at http://faq.perl.org . -------------------------------------------------------------------- 4.73: How do I print out or copy a recursive data structure? The "Data::Dumper" module on CPAN (or the 5.005 release of Perl) is great for printing out data structures. The "Storable" module on C...

Accessing hidden functions in a structure
Hi, Is there any way of accessing hidden functions in a structure? (for debugging purposes I would like to test each of the components of different structures regardless of whether they are part of the signature or not). Cheers, Maria Maria Garcia de la Banda wrote: > Hi, > > Is there any way of accessing hidden functions in a structure? (for debugging > purposes I would like to test each of the components of different structures > regardless of whether they are part of the signature or not). > > Cheers, > > Maria > SML/NJ has...

Winzip self-extract for Access Runtime install problem
Hi, I'm trying to create a self-extracting zip file from a zip file that contains the install for a distributed access application. The problem is that when I run it, I get a message saying something like "Please go to the control panel to install and configure system components". This is too vague. Does anyone know what the error message means? Obviously, this must work properly and an arbitrary users pc (since the app is distributed). Thanks in advance, Sam90 The problem is that the wrong Setup.exe is being run after the self-extractor is done unpacking. Instead of the ...

Memory footprint of a structure of structures
Hi, I have a (big) structure, which contains other structures with (sometimes) big buffers. Something like : #define BUF_SIZE 65536 #define BUF_SIZE2 32768 typedef struct { unsigned char buffer1[BUF_SIZE]; unsigned char buffer2[BUF_SIZE]; } t_buffer_head; typedef struct { unsigned char buffer1[BUF_SIZE2]; unsigned char buffer2[BUF_SIZE2]; } t_buffer_subhead; typedef struct { t_buffer_head header; t_buffer_subhead subheader; } t_buffer_s; In my use case, I have >100 structures of t_buffer_something and one big structure of these structures. I would like, at compile time ...

Conflicts after Runtime Installation
Hi There I'm new to using Office Developer and I've come across a problem. I created an installation CD for my application using Developer xp 2002 and it works fine but if I install it onto a machine with Access 2000 on it the Access has to reconfigure itself after I have used the run-time programme. Am I doing something wrong? ...

tcl/tk on Windows: "This application has requested the Runtime to terminate it in an unusual way" on quit
I have an application that uses Tk and runs on various platforms. On Windows 2000 (I don't know about XP) when the user quits (which calls quit on the root toplevel), it always exits with the following error dialog: This application has requested the Runtime to terminate it in an unusual way. Please contact the application"s support team for more information. Any idea how to prevent this? A google search shows that others have had this problem, but I didn't see any resolution. -- Russell P.S. The application need not be doing anything much at the time, though it does use...

Structure of .ST files
Please, what is the structure of a .ST file emulating an Atari ST floppy disk? The file has 738.260 B versus 726.016 on the FD. Thanks Paul ...

Apple Corporate Structure
If I want to complain to Apple about the quality of service at one of their "Authorized Service Providers" what department should I address my complaints to? And what would the department-head's title likely be? I find that a polite, articulate and concise snail-mail letter addressed to an appropriate individual is still taken seriously by large faceless corporations. Note: this isn't a complaint about Apple or AppleCare, it's a complaint about rednecks in small towns. -- Where's the Vangelis music? Pris' tongue is sticking out in in the wide s...

extract page structure from page source?
Hi, Given a page source, is there any tool that can make a sketch of the page structure? Our template is DIV based. It's easy to get lost in so many DIV's. Say, <div id="container"> can include other DIV's (e.g. nav, content, righ-column, footer, etc.). Just by staring at the page source, it's so hard to find the closing </div> for <div id="container">. Any ideas? Thanks in advance, Bing dubing@gmail.com wrote: > Hi, > > Given a page source, is there any tool that can make a sketch of the > page struc...

structures, structures and more structures (questions about nested structures)
Hi, I have the ff data types : typedef enum { VAL_LONG , VAL_DOUBLE , VAL_STRING , VAL_DATASET }ValueTypeEnum ; typedef union { long lval ; double fval ; char* sval ; void* ptr ; } Value ; typedef struct { int magic ; int version ; }Header ; typedef struct { char label[20] ; id int ; }Key ; typedef struct { Header *hdr ; char *subject ; int subject_len ; Key key ; ValueTypeEnum type ; Value value ; int text_len ; int size ; }MotherStruct ; If I have a variable declared as ff: MotherStruct *pMS = calloc(1,sizeof(MotherStruct*)) ; 1). Do I have to al...

malloc and free
If I allocate a block of memory char *p = (char*)malloc(sizeof(char)*10); afterward I want to free a number of them, say the first 3 blocks, how do I do so? If I tried free(p), the whole 10 blocks are being freed. Is there a method to free only the first few blocks without having to malloc a new block and copy the remaining ones? Thank you Kelvin Leung wrote: > > If I allocate a block of memory > char *p = (char*)malloc(sizeof(char)*10); > afterward I want to free a number of them, say the first 3 blocks, how do I > do so? If I tried free(p), the whole 10 blocks are being...

libobjc runtime from Mac OS X
I just wonder if anyone has tried to port that to windows? Hint would be very welcome Thanks Friedrich -- Please remove just-for-news- to reply via e-mail. In article <87wsg76yc5.fsf@fvl.here>, Friedrich <just-for-news-frido@q-software-solutions.de> wrote: > I just wonder if anyone has tried to port that to windows? > > Hint would be very welcome You mean Apple's specifically? Instead of the one that's available as part of gcc or the one that's available via GNUstep? -- "Harry?" Ron's voice was a mere whisper. "...

Structures #11
I have a structure data type. I would like to convert the structure to a list of variables with names which are the field names. In other words i would like to destroy the structure and replace it with variables which are the field names. Thanks "Ofer Moshe" <mosheo@bgu.ac.il> wrote in message <gjt3je$fjh$1@fred.mathworks.com>... > I have a structure data type. I would like to convert the structure to a list of variables with names which are the field names. In other words i would like to destroy the structure and replace it with variables which are the field names. ...