C :: Under-allocating Memory For A Tagged Union

Mar 6, 2015

What i'm interested in is the behavour of a struct/union constructed like this:

Code:
typedef struct {
uint64_t num1;
uint64_t num2;
} st_a;

typedef struct {
uint64_t num1;
uint32_t num2;

[Code] .....

What kind of behavour could I expect from object, in the following cases:

1. newsomestruct(0)->u.a.num1 = 2;
2. newsomestruct(1)->u.b.num1 = 2;
3. newsomestruct(0)->u.a.num2 = 2;
4. newsomestruct(1)->u.b.num2 = 2;
5. newsomestruct(0)->u.b.num1 = 2;
6. newsomestruct(1)->u.a.num1 = 2;
7. newsomestruct(0)->u.b.num2 = 2;
8. newsomestruct(1)->u.a.num2 = 2;
9. Code:

somestruct* ss1 = newsomestruct(0);
somestruct* ss2 = newsomestruct(1);
* ss1 = * ss2; 10. Code: somestruct* ss1 = newsomestruct(0);
somestruct* ss2 = newsomestruct(1);
* ss2 = * ss1;

This is what I'd expect, but I can't find any evidence online in C standards or elsewhere:

1. Works as expected, sets the value of a.num1 to 2.
2. Works as expected, sets the value of b.num1 to 2.
3. Works as expected, sets the value of a.num2 to 2.
4. Works as expected, sets the value of b.num2 to 2.
5. Works as expected, sets the value of b.num1 to 2.
6. Works as expected, sets the value of a.num1 to 2.
7. Works as expected, sets the value of b.num1 to 2.
8. Crashes/Memory Corruption, attempted to alter memory outside struct.
9. Works as expected, * ss1 == * ss2
10. Crashes/Memory Corruption, attempted to alter memory outside struct.

I've tested simular code on my machine (Xubuntu 14.04LTS compiled with gcc on -O3) and it appears to be reliable, given that you stick with acessing the type tagged in the struct or the common initial union struct members (in this case num1).

View 6 Replies


ADVERTISEMENT

C :: Dynamically Allocating Memory?

Sep 18, 2013

I have created a database for music cds:

Code:

#include<stdio.h>
#include<stdlib.h>
#define array
typedef struct cd_database

[Code]....

When I am using malloc instead of arrays the code is not working properly after exit. I have tried alot but can't came up with a way

View 5 Replies View Related

C :: Error Allocating Memory

Jun 1, 2014

Code:

# include <stdio.h>
# include <math.h>
# include <stdlib.h>
# include <malloc.h>
}

[code]...

I am compiling it on a 64 BIT ubuntu machine having 64GB ram using gcc 4.6 compiler. I am getting the following output Error allocating memory. But (914*866*2724) is approximately 8 GB, Whats wrong with the code?

View 7 Replies View Related

C++ :: Not Allocating Enough Memory To Pointer?

Jan 24, 2014

I wrote the following C++ constructor, and I get an error - BUFFER too small on strcpy_s

Trace::Trace(const char *str) {
if (str) {
int len = strlen(str);
this->m_name = new char[len+1]; // asking for 'len+1' memory elements of char
strcpy_s(m_name, len, str); // **** I get here an error "BUFFER TOO SMALL" ****

[Code] .....

m_name is a private data member of type char* .

View 3 Replies View Related

C :: Allocating Memory To Array Of Struct?

Sep 9, 2013

Do you have to allocate memory(malloc) for an array of structs? Example:

Code:
typedef struct{
char * name;
}First;
struct name{
First fname;
};
struct name Names[10];

View 7 Replies View Related

C/C++ :: Allocating Memory For 2D Array In Other Class?

Jun 10, 2014

I'm making some multi-threaded program, but thats not my problem as i've done that already. I have a class with user-functions containing a structure which then contains a two dimensional array for each user with 25 elements. So I dont want to limit the user and make the array for example with just 10 rows, but allocate the needed memory to match the amount of 'users' a potential user of my program would want. The problem is, that i know how i should allocate it using 'new int' but it just doesnt work ! It gives an error:

Error: no operator "=" matches these operands

UserStuff.h:
struct userDataStruct {
bool* isAdmin;

[Code]...

Then, in some completely other class function inside the file mentioned above: (I know i could do a function in CUsers class which could allocate the memory, but I have this function which is used for some other things and it already has the amount of max users

void OtherClass::somefunction(maxusers)
{
// This gives an error: Error: no operator "=" matches these operands
curUsers->uData.userNumbers = new int*[maxusers]; //maxusers is the int variable of max users specified by the client
// However this doesn't
for( int i = 0 ; i < maxusers ; i++ )
curUsers->uData.userNumbers[i] = new int[25]; // 25 columns, this doesnt give any error
}

I'm not really sure what I'm doing wrong. Doing this in some function from CUsers class works (without curUsers-> or with, doesn't give any error) but doing it from some other class's function doesnt.

View 11 Replies View Related

C++ :: Allocating Memory For Vectorized 2D Array?

Mar 2, 2015

I want to be able to dynamically allocate and index an array like the following: vv2d[1][2].x and vv2d[1][2].y. In order to accomplish that I have chosen to use a std::vector of a std::vector of a 2D point class.

Code:
/// Here is my templated version of a 2d point class which I have adopted from
/// one by Alexander Chernosvitov, Function Graphics, 2001 (see ogview.h)
/// http://www.codeguru.com/cpp/g-m/opengl/article.php/c5581/Function-graphics-in-3D.htm
template <typename T>

[Code]....

Boundary violation occurs as soon as vv2d[1][0].x is encountered. I believe the problem is my inability to dynamically allocate the size of the (primary) typedef vector. However, eliminating the typedef for the following does not change the result. Further examination shows the vv2d[1][0] size and capacity to be 0.

Code:
vector<vector<CPoint2D<double>>> vv2d;
vv2d.resize(3);
vv2d[0].resize(3);

View 14 Replies View Related

C :: Allocating And Freeing Memory For Array Of Structures

Jul 27, 2014

I have to allocate memory for an array of structures, and my structure looks as following:

Code:
typedef struct {
char *name;
Uint *start_pos;
Uint len;
}
example_struct;

And now I want to allocate memory, for a variable number (so an array) of example_struct, so I first do:
Code:

example struct *all_struct;
int total_num = 3;
//will be set somehow, but for the example I set it on 3 all_struct = malloc (sizeof(example_struct) * total_num);

And now, as far as I now, I will have to allocate for each field of the structure memory, in order to be able to use it later. But I have problem at this point, a problem of understanding:

- I just allocated memory for 3 structures, but don't I have to allocate then memory for each structure separately, or can I just now allocate the fields like this:

Code: all_struct[0].name = malloc.....

But if yes, why the hell this works...

View 10 Replies View Related

C++ :: Integer Pointer - Get Address Without Allocating Memory

Jun 3, 2013

I have an integer pointer and i want its address without allocating memory,

main() {
int *a;
cout<<a;
}

This is giving 00000000 and its but obvious. Now if i use address of a (&a) along with *a,

main() {
int *a;
cout<<a;
cout<<&a;
}

'cout<<a' gives me a constant address but 'cout<<&a' gives me different address.

what is the reason behind & and why behaviour of 'cout<<a' changes when using with &.

View 8 Replies View Related

C :: Using Structure In Union

May 27, 2013

I'm trying to use a structure in union in the following format:

Code:
union data
{
unsigned char All[10] ;
struct data_pkt
{
unsigned char ack;
unsigned short status;
unsigned short data_length;
unsigned char Data[5];
}format;
}adb; adb.

All has 10 bytes which is equivalent to the structure bytes. ie 6 bytes if unsigned char and 2 short i.e 4 bytes. Thus total 10 bytes is given to adb.All. When I print the struct size I get 12 bytes. This creates problem in obtaining data in union. According to the program:

adb.format.ack should have the address of adb.All[0]
adb.format.status should have the address of adb.All[1]
adb.format.data_length should have the address of adb.All[3]
adb.format.Data[0] should have the address of adb.All[5]

But in actual case this is how memory is allocated:

adb.format.ack assigned to the address of adb.All[0]
adb.format.status assigned to the address of adb.All[2]
adb.format.data_length assigned to the address of adb.All[4]
adb.format.Data[0] assigned to the address of adb.All[6]

Why this is happening? How can I solve this?

View 9 Replies View Related

C++ :: Using Union For Combining Registers

Nov 16, 2013

How I could use unions to combine registers elegantly. For example I have the 8 bit registers B and C & I have opcodes that work on each independent register such as add b, c, which is simple, but then I also have opcodes that work on both of them as if they're one like ld a, bc. I know I could go about that by just masking them together but I've seen it done with unions before & it made everything so much more simple.

View 4 Replies View Related

C++ :: Using Pointer In Union And Assigning Value

Jul 2, 2013

In the current code,We are using pointer of union and assigning value.

class sample {
union {
short *two_int;
int *four_int;
double *eight_real;
char *one_ascii;
// void *v;
}; }

Than we assign value in following way.

sample.four_int[0] = (x + xoff); ( x and xoff and y and yoff all are integer)
sample.four_int[1] = (y + yoff);

Than we write data into file. it was working fine into 32 bit machine but it is not working 64bit machine. When I compare data and found that data is divided by 4. For Ex The File generating from 32 bit machine contain 80 than 64 bit . File contain 20.

View 7 Replies View Related

C++ :: Changes In Union Typedef Not Mirrored

Sep 1, 2013

I have made VGA emulation with registers and memory in my emulator. But for some reason the writes to the union array with CPU data (register 0-8 of the VGA's Graphics Controller Registers, referenced with <GRAPHREGS>.DATA[index]) don't reflect on the union's data.

typedef union __attribute__((packed)) {
byte DATA[9]; //9 registers present!
struct //Contains the registers itself! {
//Set/Reset Register (index 00h)
union {

[code]...

what's going wrong? Have I made an error in the registers?

(In this case I write to register <GRAPHREGS>.DATA[8] (which should be the <GRAPHREGS>.REGISTERS.BITMASKREGISTER)), but the BITMASKREGISTER stays 0, while DATA[8] gets the correct value.

View 4 Replies View Related

C++ :: Assigning Values To Union?

Sep 10, 2012

I have the following C++ code

typedef union UUID {
unsigned char byte[16]; /**< Array of 16 bytes. */
unsigned int ll[2]; /**< Array of two 64-bit words. */
} UUID;

[Code] ......

The compiler complains thus

$ g++ union.cpp
union.cpp: In function "int main()":
union.cpp:15:17: warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x
union.cpp:15:17: warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x
union.cpp:15:17: error: no match for "operator=" in "entry.EntryHeader::uuid = {0, 0, 0, 2}"
union.cpp:1:20: note: candidate is: UUID& UUID:perator=(const UUID&)

How do I go about assigning values to this union in C++.

View 3 Replies View Related

C++ :: Classes Defined With Struct And Union

Mar 12, 2013

Classes defined with struct and union

Classes can be defined not only with keyword class, but also with keywords struct and union.

The concepts of class and data structure are so similar that both keywords (struct and class) can be used in C++ to declare classes (i.e. structs can also have function members in C++, not only data members). The only difference between both is that members of classes declared with the keyword struct have public access by default, while members of classes declared with the keyword class have private access. For all other purposes both keywords are equivalent.

The concept of unions is different from that of classes declared with struct and class, since unions only store one data member at a time, but nevertheless they are also classes and can thus also hold function members. The default access in union classes is public.

The above is a statement taken from a C++ tutorial. So I understand classes a bit better now but the above quote doesnt make too much sense. Is it saying that you can have a class within a class?

View 1 Replies View Related

C++ :: Pointer Of Union And Fwrite Operation

Jul 5, 2013

I have union of pointer.

union {
short *two_int;
int *four_int;
double *eight_real;
char *one_ascii;
// void *v;
};

We have write function which write into file.

fwrite (r.one_ascii, 1, i, outstr);

I found one thing,When we write function, we fill only four int in following way.

r.four_int[0] = x + xoff;
r.four_int[1] = y + yoff;

So my question,we fill four_int but write one_ascii only.As is it union of pointer. So it does not matter. I am using 64bit machine and do not have any issue in 32 bit machine.

For more information: [URL] ....

View 7 Replies View Related

C++ :: How To Find Out Which Member Of Union Is Currently Set / Active

Jan 16, 2015

how to find out which member of union is currently set/active.

exm:
union myunion{
int i;
float f;
}

if i set myunion ob{7}, it set ob.i=7;

my q? is how to find out i is set f is not set/ not acrive

View 2 Replies View Related

C++ :: How To Program Boolean Union And Intersection

Jun 19, 2014

It involves some discrete mathematics. Any code snippet to get me started?

View 3 Replies View Related

C++ :: Find Intersection / Union And Difference Of Two Sets

Feb 17, 2014

The program is to find intersection,union and difference of two sets. The program take the input correctly but after it crashes with the message that some exe is not working...

Code:
#include<iostream>
using namespace std;
void Input(int *A, int*B, int size1, int size2)
//input function {

[Code] ....

View 3 Replies View Related

C++ :: Union Of Two Vector ADT Bags - Operator Overload

Apr 30, 2014

I'm trying to come up with the union of two Vector ADT bags, so I have to overload the '+' operator, but I'm getting a bunch of error messages saying:

VectorBag.cpp: In instantiation of ‘VectorBag<ItemType> VectorBag<ItemType>::operator+(VectorBag<ItemType>) [with ItemType = int]’:
proj2.cpp:161:42: required from here
VectorBag.cpp:81:24: error: no match for ‘operator[]’ (operand types are ‘VectorBag<int>’ and ‘int’)
newBag.add(anotherBag[i]);
^
Here is the function to overload the operator:

template<class ItemType>
VectorBag<ItemType>
VectorBag<ItemType>::operator+(VectorBag<ItemType> anotherBag) {
VectorBag<ItemType> newBag;
for (int i = 0; i < anotherBag.getCurrentSize(); i++)
newBag.add(anotherBag[i]);
}

The add() function is pre-defined by me somewhere else in the code. It basically does push_back().

View 4 Replies View Related

C# :: T-SQL Multi Table Union To Call Out Data

Jul 15, 2014

I'm trying to union eleven tables to call out data. Parent table is 'Events', child tables are 'SR1Laptimes', 'SR2Laptimes' and so on (there are ten SR... tables). Primary key in all tables is EventName. Parent/Child relationship is Events.EventName/SR1Laptimes.EventName etc All tables that start with SR have the same Schema. I'm trying to call out MIN(Q1) across all table but first need to Union them I believe. Here is my code.

myCommand.CommandText = "SELECT MIN(Q1), MIN(Q2), MIN(Q3), MIN(Q4), MIN(LaptimesMinutes), MIN(LaptimesSeconds) FROM (SELECT * FROM Events UNION ALL SELECT * FROM SR1Laptimes UNION ALL SELECT * FROM SR2Laptimes) WHERE (Events.Track = @track) AND (Events.Number = @number) AND (Events.Rider = @rider)";
myCommand.Parameters.AddWithValue("@track", analysisTrackComboBox.Text);
myCommand.Parameters.AddWithValue("@number", analysisNumberComboBox.Text);
myCommand.Parameters.AddWithValue("@rider", analysisRiderComboBox.Text);

View 4 Replies View Related

C++ :: Malloc For Union Inside Structure Fails

Dec 27, 2012

I have some problem while allocating memory to a union inside structure. Below is the code i am using

ON SYSTEM1:

This works fine

ON SYSTEM2:

compiler complains saying "need structure or union type" while allocating MYSTRUCT1.

If I change:

shreyas[0].UnionAttr.struct1 = (MYSTRUCT1 *) malloc (sizeof(MYSTRUCT1)
to
shreyas[0].UnionAttr->struct1 = (MYSTRUCT1 *) malloc (sizeof(MYSTRUCT1)

This compiler on SYSTEM2 is happy. but second way does not look correct to me and compiler on system 1 complains about it. Which is the correct way to allocate memory?

If first one is correct then what should i look in for to avoid this error? Could this be an issue with compiler on SYSTEM2? If i use second method on SYSTEM2 code segfaults during malloc.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct mystruct1 {
int a;
int b;

[Code] ....

View 3 Replies View Related

C++ :: Allocating Space Only For Two Characters

Jan 15, 2013

I am allocating space only for two characters but it fits all of them, if you run this it will print the whole string literal "hello my friend". How is that possible?

I am using gcc 4.6.3., I know about strncpy().

#include<iostream>
#include<cstring>
using namespace std;
int main(){
char* str = new char[2];
strcpy(str, "hello my friend");
cout << str << endl;
return 0;
}

View 4 Replies View Related

C++ :: Declare Not Allocating Storage?

Jan 22, 2014

decalration won't allocate storage, while definition will. This is a test program:

#include <iostream>
using namespace std;
extern int ei;
int i;

[Code].....

Others are all fine in this program except ei.
compiler error: undefined reference to ei.

I understand ei is only declared so there is no memory address, but when I do ei=1, then ei completed it's definition, why still cannot use pei to get it's address?

View 9 Replies View Related

C++ :: Splitting RGBA Into Individual Bytes By Creating Union

Jan 16, 2013

I am currently working with win32 API , for image processing, one of the windows function returns RGBA ( colors ) as unsigned int , I then split it into individual bytes by creating a union ,

Code:
union colour {
unsigned int value;
unsigned char RGBA[4];
}

to spit the int into individual bytes, my Question is there a better or my convenient way of doing this.

View 6 Replies View Related

C++ :: Dynamically Allocating Multidimensional Array?

Nov 24, 2013

Working on this one from the Jumping into c++ book. The book asks that I create a multidimensional array at run time based on user input and fill it with a multiplication table

My code compiles fine but throws an uninitiated error for p when I try and run it.

Code:
void multiDimentionalMultiplication(int x, int y, int z){
int ***p;
**p = new int[x];
std::cout << "Allocating array.

[code]....

View 8 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved