Keil Logo Arm Logo

Discussion Forum

An error in allocation

Next Thread | Thread List | Previous Thread Start a Thread | Settings

Details Message
Read-Only
Author
H Matherson
Posted
27-Apr-2012 14:52 GMT
Toolset
ARM
New! An error in allocation

We have an issue with this code


struct foo {
 int NumberOfPointers;

 char *Pointers[1];
} xx;

// Allocate A Block Of Pool With Room For 100 Pointers

myHunkyStuff = malloc( sizeof(long) + 100 * sizeof (char *) );

Can anyone explain?

The H Matherson Crew

Read-Only
Author
Øyvind Kaurstad
Posted
27-Apr-2012 18:40 GMT
Toolset
ARM
New! RE: An error in allocation

What is the problem, exactly? To get good answers you need to ask good questions, and you haven't even specified if this is a compiler problem (i.e does the compiler give you errors?) or a runtime problem (i.e, the code doesn't do what you want).

That said, your code doesn't make much sense. I'm guessing that you want to have one copy of the struct, and then allocate memory for 100 pointers to char, which is then to be assigned to the member Pointers of said struct. Instead, you're allocating memory for 100 pointers to char and one long.

Please describe what it is you want to achieve, and then you might get some sensible help.

Regards
-Øyvind

Read-Only
Author
H Matherson
Posted
27-Apr-2012 19:54 GMT
Toolset
ARM
New! RE: An error in allocation

What we're trying to do is new the object whats got the number of objects and the array just like C++. It compiles great. But when we run it we get errors. For some strange unexplicable reason the last pointer is not always kept on and we dont know why.

Read-Only
Author
Per Westermark
Posted
28-Apr-2012 01:33 GMT
Toolset
ARM
New! RE: An error in allocation

If you wanted to make sure you really did get the memory you needed you should to a slight over-allocation - don't try to figure out the size of the other elements in the struct and their offsets etc. Allocate sizeof(struct) + x*sizeof(ptr). Then you do know that you have got a pointer to a block large enough, without having involved any tricks.

Read-Only
Author
Reluctant Consultant
Posted
28-Apr-2012 06:43 GMT
Toolset
ARM
New! No tricks required

Apart for an obvious error/typo in the code, the task itself is straightforward:


struct foo {
 int NumberOfPointers;

 char *Pointers[1];
} xx;

// Allocate A Block Of Pool With Room For 100 Pointers

myHunkyStuff = malloc( sizeof(xx) + (100-1)*sizeof (char *) );

You want the size of the overall structure (along with any padding that might be present between NumOfPointers and Pointers) plus an array of the 'extra to the one already in' the structure.

Next Thread | Thread List | Previous Thread Start a Thread | Settings

Keil logo

Arm logo
Important information

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies.