Structures and malloc at runtime

  • Permalink
  • submit to reddit
  • Email
  • Follow


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
Reply bigpig (1) 5/31/2007 7:38:25 PM

See related articles to this posting


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
Reply 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
Reply 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
Reply CBFalconer 5/31/2007 9:41:03 PM
comp.compilers.lcc 1243 articles. 0 followers. Post

3 Replies
132 Views

Similar Articles

[PageSpeed] 39


  • Permalink
  • submit to reddit
  • Email
  • Follow


Reply:

Similar Artilces:

Runtime Structure
Hi EveryBody! i need a information about creatting structure at runtime.... like example ..... int main() { char *a,*b; printf("Enter the structure"); scanf("%s",a); printf ("Enter The Datatype"); scanf("%s",b); create(a,b); } void create(char *F,Char *G); { struct F { G a; } } i hope u will understand this program... this example ,but i need inforamtion any possibleties to create struct and its field in runtime , that user will define.. if posssible give me reply Thanks BY CNS "chellappa" <N.Chellappa@gmail.com> ...

structure and malloc
typedef struct { int a; int b; int c; } ABC; typedef struct { int d; int e; int f; ABC *abc; } DEF; Create function should use a single call to malloc to allocate memoryfor structure DEF and its constituting structure ABC. In other words, after a call to the CreateDEF() function, the following statements should be valid and should work without segmentation violations: DEF* pDEF = CreateDEF(); pDEF-->abc-->a = 100 ; DEF *CreateDEF ( void ) { } void FreeDEF (ABC *pABC) { } friend.05 wrote: > type...

free'ing malloc'd structure with malloc'd members
In the course of an assignment, I learned the hard way that I shouldn't try to free a malloc'd member of a malloc'd structure after having freed that structure (i.e., free( structure ); free( structure->bufferspace ) ). My question is, if I free just the structure, will the (e.g.) bufferspace be freed implicitly, or do I have to (as I currently am) free the members first? Thanks. -cjl John wrote: > In the course of an assignment, I learned the hard way that I shouldn't try > to free a malloc'd member of a malloc'd structure after having freed that ...

MAllocate memory for structures?
Hi all, I have to use C-style structures for an assignement. I cannot have any methods or constructors for it. What has surprised me is that in my code, I have to allocate memory for an array of structures with malloc. Otherwise, I get a seg fault. Here's the code: struct Employee { char* name; // Pointer to character string holding name of employee. int salary; }; // Allocate the employee array; Employee* emp[20]; int ans; // return value of fscanf int size = 0; for (int i = 0; i < MAX_EMPS; i++) { //dynamically allocate memory // otherwise seg fa...

Malloc, Structure Help
Hi all, I'm working on a quick program to bring the Bible into memory from a text file. Anyway, I have three questions to ask. First, is my implementation of malloc () correct in the program to follow? Second, have I correctly passed the structure's pointer to the functions in this program? Last, how do I go about initializing the structure variables in the given function? Here's the program: *----------------------------------------* #include <stdio.h> #include <stdlib.h> struct bibtxt { char book[32]; int chapter; int verse; char text[500]; }; typedef s...

Runtime Structure Creation
Hi All, I am trying to dynamically implement (declare/define) a structure within a function. The reason being, is that this structure would contain a variable number of members of various possible types depending on what's passed to it, and then be returned via pointer to the dynamically allocated memory. I'm sure that there are various ways to do this (ie: linked lists, void types...,etc) but I can't seem to put my finger on it explicitly or pragmatically in my available resources (that tree in the forrest :-). I'm still fairly green in "the ways of C". I h...

structure malloc help
I have a structure defined as: struct channel { int chanid; int channum; char callsign[20]; char name[64]; }; I then have a global variable defined as: static struct channel *chan=NULL; I then malloc the space when I know the total number of rows (dynamic variable Total_rows) I have: if ( (chan=(struct channel*)malloc(sizeof(struct channel)*Total_rows)) = = NULL) { snprintf(buf, sizeof(buf),"Mallor Error.\n" ); free (chan); goto out; } My issue as I fill the structure the program seg faults. I...

OOP Runtime data structures
Hi, I'm working on an object-oriented programming language, and I'm unsure about the best way to implement the runtime data structures. Any input will be appreciated! 1) I don't intend to differentiate between classes and objects. That is, a class can be used just like any other object, and any object can be subclassed. I also want method invocations to be messages, so any object that responds to the same messages as another can be used in the other's place, like in Objective C or Smalltalk. So, I thought that I allocate one C-string for each unique message name, and use ...

querying runtime data structures
Hi all, I'm still absorbing all of the ideas from ILC and feel energized by the event and the discussions that followed. Thanks everybody! Something that occurred to me shortly afterward was the possibility of doing queries on my runtime data structures. This would be at a layer above an inspector, analogous to how Mac OS X 10.4's Spotlight works at a level above the file browser. Here's the problem I ran into. I ran my program and noticed that something that should have been output once was instead output eight times. I wanted to search back through the execution to find the _f...

Edit table structure in runtime
I've just installed a database on a system that only has Access 2002 Runtime [split front end/back end]. I have remote access to the system. I might need to change the table structure later, to add fields for example. The only way I can think of doing this involves sending myself the data, make the changes, and sending it back - which of course involves quite a bit of downtime. Are there any routines within Access or external programs [free/ cheaper than Access] that I could use to deal with this? Or has anyone worked around this issue previously? Many thanks Jon J-P-W <jonpwebb@...

Memory Trouble (Structures and malloc)
#include <stdio.h> #include <stdlib.h> typedef struct _oneLine { int ntoks; char **lns; }OneLine; typedef struct _codeArray { int argc; OneLine **args; }CodeArray; int main(int argc, char *argv[]) { int i, ii, iii; /* codeArray[10] */ CodeArray *c = malloc(10 * sizeof(CodeArray) ); /* CodeArray[10].args[10][10] */ for (i = 0; i < 10; ++i) { c[i].args = malloc ( 10 * sizeof(OneLine) ); for(ii = 0; ii < 10; ++ii) c[i].args[ii] = malloc ( 10 * sizeof(OneLine) ); } /* CodeArray[10...

malloc for members of a structure and a segmentation fault
I am pretty new to C and doing my first project in C. I actually read almost the entire FAQ, but can't seem to figure out this problem. I have a structure. I have a list of these structures. Inside each structure, I have two members: a list of strings, and a string. I have made a sample program below that exhibits the error I am having. I also read about Valgrind, and used it to tell me where I was getting the segmentation fault, which is really helpful. The Valgrind output is below my sample code. At line 72 (it is labeled below), I use an unitialized value and then, I try to writ...

how to allocate memory for member of structure at runtime
Hello , This is Raghu. I have a problem in declaring a structure. Consider struct hai{ int id; char sex; int age; }; here when a variable is instianted for this structure then immediately for all members memory is allocated. But I need to allocate memory for age only if sex is M else the memory should not allocate. Think you understand the query. awaiting for your reply bye take care with smile Raghu -- comp.lang.c.moderated - moderation address: clcm@plethora.net -- you must have an appropriate newsgroups line in your header for your mail to be seen, or the new...

9.4 enabling INTERNAL MALLOC at runtime
I am aware that this is an option with bind 9.4, and expected that the syntax to turn it on would be relatively easy to find. However after searching the ARM, MARC, googling, and checking the installed manpages as well as those on isc.org, I am unable to track this down. I suspect it is implemented as the -m argument to named, but this doesn't seem to appear in the docs. Has the documentation possibly not been updated in this regard? Also, what is the syntax to turn this on at runtime? ##################################################################################### This ema...

question about replication and how to keep runtime data structures consistent
Hi there, I have a question about replication on 2 servers and how to keep the application data structures consistent at both of them. Normally my application is running at the primary server while the committed transaction data are replicated to a secondary server. In case the primary server failed, the secondary server will become primary server. Berkeley DB's replication service is great help to keep the database env at secondary server consistent with primary server. However my application's high availability feature requires "hot-standby": the secondary s...

Re: 9.4 enabling INTERNAL MALLOC at runtime
> I am aware that this is an option with bind 9.4, and expected that the > syntax to turn it on would be relatively easy to find. However after > searching the ARM, MARC, googling, and checking the installed manpages > as well as those on isc.org, I am unable to track this down. > I suspect it is implemented as the -m argument to named, but this > doesn't seem to appear in the docs. > Has the documentation possibly not been updated in this regard? Also, > what is the syntax to turn this on at runtime? It is enabled where appropriate. There are multiple...

NetBIOS structure runtime check fails on WOW32 on 64 bit Windows
Hi The below routine works just fine on 32 bit Windows 2000, XP and Server 2003. But under WOW32 on a 2003 64 bit system the debug code (compiled with runtime checks) fails claiming that "Run-Time Check Failure #2 - Stack around the variable 'ncbO' was corrupted." Release version without the check seems to work ok but i want to debug. I'm using MSVC 2003 7.1.6030 and don't currently have time to convert the code to 64 bit. Here is the routine which purpose is to simulate use of "NBTSTAT -a computername" to check if a workstation is online. N...

NetBIOS structure runtime check fails on WOW32 on 64 bit Windows
Hi The below routine works just fine on 32 bit Windows 2000, XP and Server 2003. But under WOW32 on a 2003 64 bit system the debug code (compiled with runtime checks) fails claiming that "Run-Time Check Failure #2 - Stack around the variable 'ncbO' was corrupted." Release version without the check seems to work ok but i want to debug. I'm using MSVC 2003 7.1.6030 and don't currently have time to convert the code to 64 bit. Here is the routine which purpose is to simulate use of "NBTSTAT -a computername" to check if a workstation is onl...

Memory management. "USE INTERNAL MALLOC" is now runtime selectable.
Hello! I found it on http://www.isc.org/index.pl?/sw/bind/view/?release=9.4.1-P1 How can I change the type of MALLOC in runtime without recompile src? --- Dmitry Rybin ...

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...

to malloc or not to malloc??
I have this code: void calc(int *ip) { int temp = 333; *ip = temp; } int main(void) { int a; calc(&a); printf("a's value: %d\n", a); return 0; } it prints the right result but I have learned not to trust this! My question is can I always be sure that the content of ip = temp? The reason I ask is that int temp is allocated on the stack and after calc returns temp no longer exists and therefore I thought that printing a in main would just by coincidence print the right result. Le 30-03-2006, Johs32 <dfgdg@dsf.com> a...

to malloc or not to malloc?
I used to program C all the time, but that was years ago. Since then, continued use of languages like Java that take care of memory management have made me soft and flabby. Now I have to code something in C, and I get the feeling that I'm courting memory leaks and segmentation faults at every turn... I'm writing a (Flex/Bison) parser that reads some serialized representation of an arbitrarily complex C data structure, and cranks out the "revived" data structure at the other end. So this code must generate a ton of C data elements (integers, floats, strings, etc.), and ...

indexing structure of structures
Hello group, I am analyzing a bunch of data from an experimental series. The analysis from each experiment (numbers a,b,c,... etc) is stored in a structure. For reasons that have little to do with foresight and expedience, I decided to store all the individual structures in one large structure (This allows me to add some more fluff). My problem is how to extract the parameter 'a' to plot it. I was hoping that an array indexing method such as outer_struct.([1,4,8,12]).a would work, but it does not. So I am re-packaging the outer structure as a vector of inner_structures. Am I m...

creating structures from structures
I have two cell arrays, lists of variable names that I would like to create in a structure, so I can store data in them. Example: test1 = {'red'; 'yellow'; 'black';} test2 = {'one'; 'two'; 'three'; 'four';} To be stored in a structure, like: test3 |_ .one |_ .two |_ .three |_ .four |________.red | |_ .one | |_ .two | |_ .three | |_ .four | |________.yellow | |_ .one | |_ .two | |_ .three | |_ .four | |________.black |_ .one |_ .two |_ .three |_ .four ...