Search Results

Search found 976 results on 40 pages for 'typedef'.

Page 12/40 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • A queue in C using structs and dynamic memory allocation (linked list)

    - by Martin Pugh
    I am tasked with making a queue data structure in C, as a linked list. Our lecturer gave us a large amount of code to implement a stack, but we have to adapt it to create a queue. The code our lecturer gave us ends up not compiling and segfaulting at the exact same point as the code I wrote for the queue. I'm very new to structs, malloc and C in general, so there could be something painfully obvious I've overlooked. Here is the code I am using: #include <stdio.h> #include <stdlib.h> struct node{ int data; //contains the actual data struct node *prev; //pointer to previous node (Closer to front) struct node *next; //pointer to next node (Closer to back) }; typedef struct node *Nodepointer; struct queue{ Nodepointer front; Nodepointer back; }; typedef struct queue *Queuepointer; main(){ Queuepointer myqueue; //create a queue called myqueue init(myqueue); //initialise the queue Nodepointer new = (Nodepointer)malloc(sizeof(struct node)); myqueue->front = new; } int init(Queuepointer q){ q = (Queuepointer)malloc(sizeof(struct queue)); q->front = NULL; q->back = NULL; } The idea is that the queue struct 'contains' the first and last nodes in a queue, and when a node is created, myqueue is updated. However, I cannot even get to that part (pop and push are written but omitted for brevity). The code is segfaulting at the line myqueue->front = new; with the following gdb output: Program received signal SIGSEGV, Segmentation fault. 0x08048401 in main () at queue.c:27 27 myqueue->front = new; Any idea what I'm doing wrong?

    Read the article

  • PInvokeStackImbalance -- C# with offreg.dll ( windows ddk7 )

    - by user301185
    I am trying to create an offline registry in memory using the offreg.dll provided in the windows ddk 7 package. You can find out more information on the offreg.dll here: MSDN Currently, while attempted to create the hive using ORCreateHive, I receive the following error: "Managed Debugging Assistant 'PInvokeStackImbalance' has detected a problem. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature." Here is the offreg.h file containing ORCreateHive: typedef PVOID ORHKEY; typedef ORHKEY *PORHKEY; VOID ORAPI ORGetVersion( __out PDWORD pdwMajorVersion, __out PDWORD pdwMinorVersion ); DWORD ORAPI OROpenHive ( __in PCWSTR lpHivePath, __out PORHKEY phkResult ); DWORD ORAPI ORCreateHive ( __out PORHKEY phkResult ); DWORD ORAPI ORCloseHive ( __in ORHKEY Handle ); The following is my C# code attempting to call the .dll and create the pointer for future use. using System.Runtime.InteropServices; namespace WindowsFormsApplication6 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } [DllImport("offreg.dll", CharSet = CharSet.Auto, EntryPoint = "ORCreateHive", SetLastError=true, CallingConvention = CallingConvention.StdCall)] public static extern IntPtr ORCreateHive2(); private void button1_Click(object sender, EventArgs e) { try { IntPtr myHandle = ORCreateHive2(); } catch (Exception r) { MessageBox.Show(r.ToString()); } } } } I have been able to create pointers in the past with no issue utilizing user32.dll, icmp.dll, etc. However, I am having no such luck with offreg.dll. Thank you.

    Read the article

  • memory alignment within gcc structs

    - by Mumbles
    I am porting an application to an ARM platform in C, the application also runs on an x86 processor, and must be backward compatible. I am now having some issues with variable alignment. I have read the gcc manual for __attribute__((aligned(4),packed)) I interpret what is being said as the start of the struct is aligned to the 4 byte boundry and the inside remains untouched because of the packed statement. originally I had this but occasionally it gets placed unaligned with the 4 byte boundary. typedef struct { unsigned int code; unsigned int length; unsigned int seq; unsigned int request; unsigned char nonce[16]; unsigned short crc; } __attribute__((packed)) CHALLENGE; so I change it to this. typedef struct { unsigned int code; unsigned int length; unsigned int seq; unsigned int request; unsigned char nonce[16]; unsigned short crc; } __attribute__((aligned(4),packed)) CHALLENGE; The understand I stated earlier seems to be incorrect as both the struct is now aligned to a 4 byte boundary, and and the inside data is now aligned to a four byte boundary, but because of the endianess, the size of the struct has increased in size from 42 to 44 bytes. This size is critical as we have other applications that depend on the struct being 42 bytes. Could some describe to me how to perform the operation that I require. Any help is much appreciated.

    Read the article

  • How to pass parameters to manage_shared_memory.construct() in Boost.Interprocess

    - by recipriversexclusion
    I've stared at the Boost.Interprocess documentation for hours but still haven't been able to figure this out. In the doc, they have an example of creating a vector in shared memory like so: //Define an STL compatible allocator of ints that allocates from the managed_shared_memory. //This allocator will allow placing containers in the segment typedef allocator<int, managed_shared_memory::segment_manager> ShmemAllocator; //Alias a vector that uses the previous STL-like allocator so that allocates //its values from the segment typedef vector<int, ShmemAllocator> MyVector; int main(int argc, char *argv[]) { //Create a new segment with given name and size managed_shared_memory segment(create_only, "MySharedMemory", 65536); //Initialize shared memory STL-compatible allocator const ShmemAllocator alloc_inst (segment.get_segment_manager()); //Construct a vector named "MyVector" in shared memory with argument alloc_inst MyVector *myvector = segment.construct<MyVector>("MyVector")(alloc_inst); Now, I understand this. What I'm stuck is how to pass a second parameter to segment.construct() to specify the number of elements. The interprocess document gives the prototype for construct() as MyType *ptr = managed_memory_segment.construct<MyType>("Name") (par1, par2...); but when I try MyVector *myvector = segment.construct<MyVector>("MyVector")(100, alloc_inst); I get compilation errors. My questions are: Who actually gets passed the parameters par1, par2 from segment.construct, the constructor of the object, e.g. vector? My understanding is that the template allocator parameter is being passed. Is that correct? How can I add another parameter, in addition to alloc_inst that is required by the constructor of the object being created in shared memory? There's very little information other than the terse Boost docs on this.

    Read the article

  • c++ d3d hooking - COM vtable

    - by Mango
    Trying to make a Fraps type program. See comment for where it fails. #include "precompiled.h" typedef IDirect3D9* (STDMETHODCALLTYPE* Direct3DCreate9_t)(UINT SDKVersion); Direct3DCreate9_t RealDirect3DCreate9 = NULL; typedef HRESULT (STDMETHODCALLTYPE* CreateDevice_t)(UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviorFlags, D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DDevice9** ppReturnedDeviceInterface); CreateDevice_t RealD3D9CreateDevice = NULL; HRESULT STDMETHODCALLTYPE HookedD3D9CreateDevice(UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviorFlags, D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DDevice9** ppReturnedDeviceInterface) { // this call makes it jump to HookedDirect3DCreate9 and crashes. i'm doing something wrong HRESULT ret = RealD3D9CreateDevice(Adapter, DeviceType, hFocusWindow, BehaviorFlags, pPresentationParameters, ppReturnedDeviceInterface); return ret; } IDirect3D9* STDMETHODCALLTYPE HookedDirect3DCreate9(UINT SDKVersion) { MessageBox(0, L"Creating d3d", L"", 0); IDirect3D9* d3d = RealDirect3DCreate9(SDKVersion); UINT_PTR* pVTable = (UINT_PTR*)(*((UINT_PTR*)d3d)); RealD3D9CreateDevice = (CreateDevice_t)pVTable[16]; DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourAttach(&(PVOID&)RealD3D9CreateDevice, HookedD3D9CreateDevice); if (DetourTransactionCommit() != ERROR_SUCCESS) { MessageBox(0, L"failed to create createdev hook", L"", 0); } return d3d; } bool APIENTRY DllMain(HINSTANCE hModule, DWORD fdwReason, LPVOID lpReserved) { if (fdwReason == DLL_PROCESS_ATTACH) { MessageBox(0, L"", L"", 0); RealDirect3DCreate9 = (Direct3DCreate9_t)GetProcAddress(GetModuleHandle(L"d3d9.dll"), "Direct3DCreate9"); DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourAttach(&(PVOID&)RealDirect3DCreate9, HookedDirect3DCreate9); DetourTransactionCommit(); } // TODO detach hooks return true; }

    Read the article

  • Pointer initialization

    - by SoulBeaver
    Sorry if this question has been asked before. On my search through SO I didn't find one that asked what I wanted to know. Basically, when I have this: typedef struct node { int data; node *node; } *head; and do node *newItem = new node; I am under the impression that I am declaring and reserving space, but not defining, a pointer to struct node, is that correct? So when I do newItem->data = 100 and newItem->next = 0 I get confused. newItem = 0would declare what exactly? Both data and next? The object as a whole? I'm especially confused when I use typedef. Which part is the macro? I assume node because that's how I call it, but why do I need it? Finally, what happens when I do: node *temp; temp = new node; temp = head->next; head->next = newItem; newItem->next = temp; I mean, head-next is a pointer pointing to object newItem, so I assume not to newItem.data or next themselves. So how can I use an uninitialized pointer that I described above safely like here? is head now not pointing to an uninitialized pointer?

    Read the article

  • How `is_base_of` works?

    - by Alexey Malistov
    Why the following code works? typedef char (&yes)[1]; typedef char (&no)[2]; template <typename B, typename D> struct Host { operator B*() const; operator D*(); }; template <typename B, typename D> struct is_base_of { template <typename T> static yes check(D*, T); static no check(B*, int); static const bool value = sizeof(check(Host<B,D>(), int())) == sizeof(yes); }; //Test sample class Base {}; class Derived : private Base {}; //Exspression is true. int test[is_base_of<Base,Derived>::value && !is_base_of<Derived,Base>::value]; Note that B is private base. Note that operator B*() is const. How does this work? Why this works? Why static yes check(D*, T); is better than static yes check(B*, int); ?

    Read the article

  • C++ boost mpl vector

    - by Gokul
    I understand that the following code won't work, as i is a runtime parameter and not a compile time parameter. But i want to know, whether there is a way to achieve the same. i have a list of classes and i need to call a template function, with each of these classes. void GucTable::refreshSessionParams() { typedef boost::mpl::vector< SessionXactDetails, SessionSchemaInfo > SessionParams; for( int i = 0; i < boost::mpl::size<SessionParams>::value; ++i ) boost::mpl::at<SessionParams, i>::type* sparam = g_getSessionParam< boost::mpl::at<SessionParams, i>::type >(); sparam->updateFromGucTable(this); } } Can someone suggest me a easy and elegant way to perform the same? i need to iterate through the mpl::vector and use the type to call a global function and then use that parameter to do some run-time operations. Thanks in advance, Gokul. Working code typedef boost::mpl::vector< SessionXactDetails, SessionSchemaInfo > SessionParams; class GucSessionIterator { private: GucTable& m_table; public: GucSessionIterator(GucTable& table) :m_table(table) { } template< typename U > void operator()(const U& ) { g_getSessionParam<U>()->updateFromGucTable(m_table); } }; void GucTable::refreshSessionParams() { boost::mpl::for_each< SessionParams >( GucSessionIterator(*this) ); return; }

    Read the article

  • RBG to CbyCr conversion code

    - by user1446688
    I am wondering why this code does not work. Basically it is supposed to convert between RGB and CbYCr. When I convert from RGB to CbYCr then back to RGB I do not get the original RGB values. What is wrong with this code? #define MIN(a,b) (((a)<(b))?(a):(b)) #define MAX(a,b) (((a)(b))?(a):(b)) struct _rgb { int R; int G; int B; }; typedef struct _rgb rgb; struct _cbycr { int Cb; int Y; int Cr; }; typedef struct _cbycr cbycr; void cbycr2rgb(rgb *c, double Y, double Cb, double Cr) { int r = (int)(Y + 1.40200 * (Cr - 0x80)); int g = (int)(Y - 0.34414 * (Cb - 0x80) - 0.71414 * (Cr - 0x80)); int b = (int)(Y + 1.77200 * (Cb - 0x80)); c->R = MAX(0, MIN(255, r)); c->G = MAX(0, MIN(255, g)); c->B = MAX(0, MIN(255, b)); } void rgb2cbycr(cbycr *c, int R, int G, int B) { c->Y = (int)(0.299 * R + 0.587 * G + 0.114 * B); c->Cb = (int)(-0.16874 * R - 0.33126 * G + 0.50000 * B); c->Cr =(int)(0.50000 * R - 0.41869 * G - 0.08131 * B); } int main() { cbycr _cbycr; rgb _rgb; _rgb.R = 50; _rgb.G = 50; _rgb.B = 50; rgb2cbycr(&_cbycr, _rgb.R, _rgb.G, _rgb.B); cbycr2rgb(&_rgb, _cbycr.Y, _cbycr.Cb, _cbycr.Cr); printf("rgb=%d %d %d\n", _rgb.R, _rgb.G, _rgb.B); return 0; } output: rgb=0 185 0

    Read the article

  • Declaration, allocation and assignment of an array of pointers to function pointers

    - by manneorama
    Hello Stack Overflow! This is my first post, so please be gentle. I've been playing around with C from time to time in the past. Now I've gotten to the point where I've started a real project (a 2D graphics engine using SDL, but that's irrelevant for the question), to be able to say that I have some real C experience. Yesterday, while working on the event system, I ran into a problem which I couldn't solve. There's this typedef, //the void parameter is really an SDL_Event*. //but that is irrelevant for this question. typedef void (*event_callback)(void); which specifies the signature of a function to be called on engine events. I want to be able to support multiple event_callbacks, so an array of these callbacks would be an idea, but do not want to limit the amount of callbacks, so I need some sort of dynamic allocation. This is where the problem arose. My first attempt went like this: //initial size of callback vector static const int initial_vecsize = 32; //our event callback vector static event_callback* vec = 0; //size static unsigned int vecsize = 0; void register_event_callback(event_callback func) { if (!vec) __engine_allocate_vec(vec); vec[vecsize++] = func; //error here! } static void __engine_allocate_vec(engine_callback* vec) { vec = (engine_callback*) malloc(sizeof(engine_callback*) * initial_vecsize); } First of all, I have omitted some error checking as well as the code that reallocates the callback vector when the number of callbacks exceed the vector size. However, when I run this code, the program crashes as described in the code. I'm guessing segmentation fault but I can't be sure since no output is given. I'm also guessing that the error comes from a somewhat flawed understanding on how to declare and allocate an array of pointers to function pointers. Please Stack Overflow, guide me.

    Read the article

  • Deleting a node from linked list in C

    - by LuckySlevin
    My problem is deleting a node from linked list. I have two structs : typedef struct inner_list { int count; char word[100]; inner_list*next; } inner_list; typedef struct outer_list { char word [100]; inner_list * head; int count; outer_list * next; } outer_list; My problem is in deleting a node from outer_list linked list. For example when user entered aaa to delete, delete function should find the node with outer_list->word = aaa and delete this node and reconnect the list again. I tried the below code to do this. but After finding and deleting I'm losing the list. I don't know what's wrong. Please notice that outer_list have also a linked list of inner_list inside. void delnode(outer_list *head,char num[100]) { outer_list *temp, *m; temp=head; while(temp!=NULL) { if(strcmp(temp->word==num)==0) { if(temp==head) { head=temp->next; free(temp); return; } else { m->next=temp->next; free(temp); return; } }else { m=temp; temp= temp->next; } } printf(" ELEMENT %s NOT FOUND ", num); } What are your ideas about this?

    Read the article

  • Send C++ Structure to MSMQ Message

    - by Gobalakrishnan
    Hi, I am trying to send the below structure through MSMQ Message typedef struct { char cfiller[7]; short MsgCode; char cfiller1[11]; short MsgLength; char cfiller2[2]; } MESSAGECODE; typedef struct { MESSAGECODE Header; char DealerId[16]; char GroupId[16]; long Token; short Periodicity; double Deposit; double GrossExposureLimit; double NetExposureLimit; double NetSaleExposureLimit; double NetPositionLimit; double TurnoverLimit; double PendingOrdersLimit; double MTMLossLimit; double MaxSingleTransValue; long MaxSingleTransQty; double IMLimit; long NetQuantityLimit; } LIMITUPDATE; void main() { // // create queue // open queue // send message // OleInitialize(NULL); // have to init OLE // // declare some variables // IMSMQQueueInfoPtr qinfo("MSMQ.MSMQQueueInfo"); IMSMQQueuePtr qSend; IMSMQMessagePtr m("MSMQ.MSMQMessage"); LIMITUPDATE l1; l1.Header.MsgCode=26001; l1.Header.MsgLength=150; qinfo->PathName = ".\\private$\\q99"; m->Body = l1; qSend = qinfo->Open(MQ_SEND_ACCESS, MQ_DENY_NONE); m->Send(qSend); qSend->Close(); } while compiling i am getting the following error. Error 2 error C2664: 'IMSMQMessage::PutBody' : cannot convert parameter 1 from 'LIMITUPDATE' to 'const _variant_t &' c:\temp\msmq\msmq.cpp 58 msmq thank you.

    Read the article

  • Compilation errors calling find_if using a functor

    - by Jim Wong
    We are having a bit of trouble using find_if to search a vector of pairs for an entry in which the first element of the pair matches a particular value. To make this work, we have defined a trivial functor whose operator() takes a pair as input and compares the first entry against a string. Unfortunately, when we actually add a call to find_if using an instance of our functor constructed using a temporary string value, the compiler produces a raft of error messages. Oddly (to me, anyway), if we replace the temporary with a string that we've created on the stack, things seem to work. Here's what the code (including both versions) looks like: typedef std::pair<std::string, std::string> MyPair; typedef std::vector<MyPair> MyVector; struct MyFunctor: std::unary_function <const MyPair&, bool> { explicit MyFunctor(const std::string& val) : m_val(val) {} bool operator() (const MyPair& p) { return p.first == m_val; } const std::string m_val; }; bool f(const char* s) { MyFunctor f(std::string(s)); // ERROR // std::string str(s); // MyFunctor f(str); // OK MyVector vec; MyVector::const_iterator i = std::find_if(vec.begin(), vec.end(), f); return i != vec.end(); } And here's what the most interesting error message looks like: /usr/include/c++/4.2.1/bits/stl_algo.h:260: error: conversion from ‘std::pair, std::allocator , std::basic_string, std::allocator ’ to non-scalar type ‘std::string’ requested Because we have a workaround, we're mostly curious as to why the first form causes problems. I'm sure we're missing something, but we haven't been able to figure out what it is.

    Read the article

  • Linked list example using threads

    - by Carl_1789
    I have read the following code of using CRITICAL_SECTION when working with multiple threads to grow a linked list. what would be the main() part which uses two threads to add to linked list? #include <windows.h> typedef struct _Node { struct _Node *next; int data; } Node; typedef struct _List { Node *head; CRITICAL_SECTION critical_sec; } List; List *CreateList() { List *pList = (List*)malloc(sizeof(pList)); pList->head = NULL; InitializeCriticalSection(&pList->critical_sec); return pList; } void AddHead(List *pList, Node *node) { EnterCriticalSection(&pList->critical_sec); node->next = pList->head; pList->head = node; LeaveCriticalSection(&pList->critical_sec); } void Insert(List *pList, Node *afterNode, Node *newNode) { EnterCriticalSection(&pList->critical_sec); if (afterNode == NULL) { AddHead(pList, newNode); } else { newNode->next = afterNode->next; afterNode->next = newNode; } LeaveCriticalSection(&pList->critical_sec); } Node *Next(List *pList, Node *node) { Node* next; EnterCriticalSection(&pList->critical_sec); next = node->next; LeaveCriticalSection(&pList->critical_sec); return next; }

    Read the article

  • How to create a generic C free function .

    - by nomemory
    I have some C structures related to a 'list' data structure. They look like this. struct nmlist_element_s { void *data; struct nmlist_element_s *next; }; typedef struct nmlist_element_s nmlist_element; struct nmlist_s { void (*destructor)(void *data); int (*cmp)(const void *e1, const void *e2); unsigned int size; nmlist_element *head; nmlist_element *tail; }; typedef struct nmlist_s nmlist; This way I can have different data types being hold in "nmlist_element-data" . The "constructor" (in terms of OOP) has the following signature: nmlist *nmlist_alloc(void (*destructor)(void *data)); Where "destructor" is specific function that de-allocated "data" (being hold by the nmlist_element). If I want to have a list containing integers as data, my "destructor" would like this: void int_destructor(void *data) { free((int*)data); } Still i find it rather "unfriendly" for me to write a destructor functions for every simple primitive data type. So is there a trick to write something like this ? (for primitives): void "x"_destructor(void *data, "x") { free(("x" *)data); } PS: I am not a macro fan myself, and in my short experience regarding C, i don't use them, unless necessary.

    Read the article

  • handling pointer to member functions within hierachy in C++

    - by anatoli
    Hi, I'm trying to code the following situation: I have a base class providing a framework for handling events. I'm trying to use an array of pointer-to-member-functions for that. It goes as following: class EH { // EventHandler virtual void something(); // just to make sure we get RTTI public: typedef void (EH::*func_t)(); protected: func_t funcs_d[10]; protected: void register_handler(int event_num, func_t f) { funcs_d[event_num] = f; } public: void handle_event(int event_num) { (this->*(funcs_d[event_num]))(); } }; Then the users are supposed to derive other classes from this one and provide handlers: class DEH : public EH { public: typedef void (DEH::*func_t)(); void handle_event_5(); DEH() { func_t f5 = &DEH::handle_event_5; register_handler(5, f5); // doesn't compile ........ } }; This code wouldn't compile, since DEH::func_t cannot be converted to EH::func_t. It makes perfect sense to me. In my case the conversion is safe since the object under this is really DEH. So I'd like to have something like that: void EH::DEH_handle_event_5_wrapper() { DEH *p = dynamic_cast<DEH *>(this); assert(p != NULL); p->handle_event_5(); } and then instead of func_t f5 = &DEH::handle_event_5; register_handler(5, f5); // doesn't compile in DEH::DEH() put register_handler(5, &EH::DEH_handle_event_5_wrapper); So, finally the question (took me long enough...): Is there a way to create those wrappers (like EH::DEH_handle_event_5_wrapper) automatically? Or to do something similar? What other solutions to this situation are out there? Thanks.

    Read the article

  • Boost Binary Endian parser not working?

    - by Hai
    I am studying how to use boost spirit Qi binary endian parser. I write a small test parser program according to here and basics examples, but it doesn't work proper. It gave me the msg:"Error:no match". Here is my code. #include "boost/spirit/include/qi.hpp" #include "boost/spirit/include/phoenix_core.hpp" #include "boost/spirit/include/phoenix_operator.hpp" #include "boost/spirit/include/qi_binary.hpp" // parsing binary data in various endianness template '<'typename P, typename T void binary_parser( char const* input, P const& endian_word_type, T& voxel, bool full_match = true) { using boost::spirit::qi::parse; char const* f(input); char const* l(f + strlen(f)); bool result1 = parse(f,l,endian_word_type,voxel); bool result2 =((!full_match) || (f ==l)); if ( result1 && result2) { //doing nothing, parsing data is pass to voxel alreay } else { std::cerr << "Error: not match!!" << std::endl; exit(1); } } typedef boost::uint16_t bs_int16; typedef boost::uint32_t bs_int32; int main ( int argc, char *argv[] ) { namespace qi = boost::spirit::qi; namespace ascii = boost::spirit::ascii; using qi::big_word; using qi::big_dword; boost::uint32_t ui; float uf; binary_parser("\x01\x02\x03\x04",big_word,ui); assert(ui=0x01020304); binary_parser("\x01\x02\x03\x04",big_word,uf); assert(uf=0x01020304); return 0; }' I almost copy the example, but why this binary parser doesn't work. I use Mac OS 10.5.8 and gcc 4.01 compiler.

    Read the article

  • Hashtable resizing leaks memory

    - by thpetrus
    I wrote a hashtable and it basically consists of these two structures: typedef struct dictEntry { void *key; void *value; struct dictEntry *next; } dictEntry; typedef struct dict { dictEntry **table; unsigned long size; unsigned long items; } dict; dict.table is a multidimensional array, which contains all the stored key/value pair, which again are a linked list. If half of the hashtable is full, I expand it by doubling the size and rehashing it: dict *_dictRehash(dict *d) { int i; dict *_d; dictEntry *dit; _d = dictCreate(d->size * 2); for (i = 0; i < d->size; i++) { for (dit = d->table[i]; dit != NULL; dit = dit->next) { _dictAddRaw(_d, dit); } } /* FIXME memory leak because the old dict can never be freed */ free(d); // seg fault return _d; } The function above uses the pointers from the old hash table and stores it in the newly created one. When freeing the old dict d a Segmentation Fault occurs. How am I able to free the old hashtable struct without having to allocate the memory for the key/value pairs again?

    Read the article

  • Impossible to be const-correct when combining data and it's lock?

    - by Graeme
    I've been looking at ways to combine a piece of data which will be accessed by multiple threads alongside the lock provisioned for thread-safety. I think I've got to a point where I don't think its possible to do this whilst maintaining const-correctness. Take the following class for example: template <typename TType, typename TMutex> class basic_lockable_type { public: typedef TMutex lock_type; public: template <typename... TArgs> explicit basic_lockable_type(TArgs&&... args) : TType(std::forward<TArgs...>(args)...) {} TType& data() { return data_; } const TType& data() const { return data_; } void lock() { mutex_.lock(); } void unlock() { mutex_.unlock(); } private: TType data_; mutable TMutex mutex_; }; typedef basic_lockable_type<std::vector<int>, std::mutex> vector_with_lock; In this I try to combine the data and lock, marking mutex_ as mutable. Unfortunately this isn't enough as I see it because when used, vector_with_lock would have to be marked as mutable in order for a read operation to be performed from a const function which isn't entirely correct (data_ should be mutable from a const). void print_values() const { std::lock_guard<vector_with_lock>(values_); for(const int val : values_) { std::cout << val << std::endl; } } vector_with_lock values_; Can anyone see anyway around this such that const-correctness is maintained whilst combining data and lock? Also, have I made any incorrect assumptions here?

    Read the article

  • Using shared_ptr to implement RCU (read-copy-update)?

    - by yongsun
    I'm very interested in the user-space RCU (read-copy-update), and trying to simulate one via tr1::shared_ptr, here is the code, while I'm really a newbie in concurrent programming, would some experts help me to review? The basic idea is, reader calls get_reading_copy() to gain the pointer of current protected data (let's say it's generation one, or G1). writer calls get_updating_copy() to gain a copy of the G1 (let's say it's G2), and only one writer is allowed to enter the critical section. After the updating is done, writer calls update() to do a swap, and make the m_data_ptr pointing to data G2. The ongoing readers and the writer now hold the shared_ptr of G1, and either a reader or a writer will eventually deallocate the G1 data. Any new readers would get the pointer to G2, and a new writer would get the copy of G2 (let's say G3). It's possible the G1 is not released yet, so multiple generations of data my co-exists. template <typename T> class rcu_protected { public: typedef T type; typedef std::tr1::shared_ptr<type> rcu_pointer; rcu_protected() : m_data_ptr (new type()) {} rcu_pointer get_reading_copy () { spin_until_eq (m_is_swapping, 0); return m_data_ptr; } rcu_pointer get_updating_copy () { spin_until_eq (m_is_swapping, 0); while (!CAS (m_is_writing, 0, 1)) {/* do sleep for back-off when exceeding maximum retry times */} rcu_pointer new_data_ptr(new type(*m_data_ptr)); // as spin_until_eq does not have memory barrier protection, // we need to place a read barrier to protect the loading of // new_data_ptr not to be re-ordered before its construction _ReadBarrier(); return new_data_ptr; } void update (rcu_pointer new_data_ptr) { while (!CAS (m_is_swapping, 0, 1)) {} m_data_ptr.swap (new_data_ptr); // as spin_until_eq does not have memory barrier protection, // we need to place a write barrier to protect the assignments of // m_is_writing/m_is_swapping be re-ordered bofore the swapping _WriteBarrier(); m_is_writing = 0; m_is_swapping = 0; } private: volatile long m_is_writing; volatile long m_is_swapping; rcu_pointer m_data_ptr; };

    Read the article

  • lambda traits inconsistency across C++0x compilers

    - by Sumant
    I observed some inconsistency between two compilers (g++ 4.5, VS2010 RC) in the way they match lambdas with partial specializations of class templates. I was trying to implement something like boost::function_types for lambdas to extract type traits. Check this for more details. In g++ 4.5, the type of the operator() of a lambda appears to be like that of a free standing function (R (*)(...)) whereas in VS2010 RC, it appears to be like that of a member function (R (C::*)(...)). So the question is are compiler writers free to interpret any way they want? If not, which compiler is correct? See the details below. template <typename T> struct function_traits : function_traits<decltype(&T::operator())> { // This generic template is instantiated on both the compilers as expected. }; template <typename R, typename C> struct function_traits<R (C::*)() const> { // inherits from this one on VS2010 RC typedef R result_type; }; template <typename R> struct function_traits<R (*)()> { // // inherits from this one g++ 4.5 typedef R result_type; }; int main(void) { auto lambda = []{}; function_traits<decltype(lambda)>::result_type *r; // void * } This program compiles on both g++ 4.5 and VS2010 but the function_traits that are instantiated are different as noted in the code.

    Read the article

  • How to fix error - "@interface interfaceName : someEnumeration" gives error "cannot find interface '

    - by Paul V
    How can I solve "cannot find interface declaration 'someEnumeration', superclass of 'interfaceName'" error? What steps will reproduce the problem? Compiling Wsdl2ObjC Targeting groupwise.wsdl file Fixing non-valid file names of output csource code like ".h" + ".m" and objects inside source files Moving up one of the @interface BEFORE it was used futher in code! What is the expected output? Something working What do you see instead? 33 errors. "Inherited" from only 3 similar Inheritances of a typedef enum object by a class. All errors are typical: typedef enum types_StatusTrackingOptions { types_StatusTrackingOptions_none = 0, types_StatusTrackingOptions_None, types_StatusTrackingOptions_Delivered, types_StatusTrackingOptions_DeliveredAndOpened, types_StatusTrackingOptions_All, } types_StatusTrackingOptions; types_StatusTrackingOptions types_StatusTrackingOptions_enumFromString(NSString *string); NSString * types_StatusTrackingOptions_stringFromEnum(types_StatusTrackingOptions enumValue); @interface types_StatusTracking : types_StatusTrackingOptions { ... and here I'm having error "cannot find interface declaration for 'types_StatusTrackingOptions', superclass of 'types_StatusTracking'". What version of the product are you using? On what operating system? Wsdl2ObjC - rev 168, OS - Mac OS X 10.6.2, iPhone SDK - 3.2, Simulator - v. 3.1.2 - 3.1.3, wsdl - for GroupWise v.8, NDK released 2008-12-23, wsdl and xsd files are attached. P.S. GroupWise.wsdl + .xsd files could be downloaded from http://code.google.com/p/wsdl2objc/issues/detail?id=99

    Read the article

  • Macro to improve callback registration readability

    - by Warren Seine
    I'm trying to write a macro to make a specific usage of callbacks in C++ easier. All my callbacks are member functions and will take this as first argument and a second one whose type inherits from a common base class. The usual way to go is: register_callback(boost::bind(&my_class::member_function, this, _1)); I'd love to write: register_callback(HANDLER(member_function)); Note that it will always be used within the same class. Even if typeof is considered as a bad practice, it sounds like a pretty solution to the lack of __class__ macro to get the current class name. The following code works: typedef typeof(*this) CLASS; boost::bind(& CLASS :: member_function, this, _1)(my_argument); but I can't use this code in a macro which will be given as argument to register_callback. I've tried: #define HANDLER(FUN) \ boost::bind(& typeof(*this) :: member_function, this, _1); which doesn't work for reasons I don't understand. Quoting GCC documentation: A typeof-construct can be used anywhere a typedef name could be used. My compiler is GCC 4.4, and even if I'd prefer something standard, GCC-specific solutions are accepted.

    Read the article

  • C++ Declarative Parsing Serialization

    - by Martin York
    Looking at Java and C# they manage to do some wicked processing based on special languaged based anotation (forgive me if that is the incorrect name). In C++ we have two problems with this: 1) There is no way to annotate a class with type information that is accessable at runtime. 2) Parsing the source to generate stuff is way to complex. But I was thinking that this could be done with some template meta-programming to achieve the same basic affect as anotations (still just thinking about it). Like char_traits that are specialised for the different types an xml_traits template could be used in a declaritive way. This traits class could be used to define how a class is serialised/deserialized by specializing the traits for the class you are trying to serialize. Example Thoughs: template<typename T> struct XML_traits { typedef XML_Empty Children; }; template<> struct XML_traits<Car> { typedef boost::mpl::vector<Body,Wheels,Engine> Children; }; template<typename T> std::ostream& Serialize(T const&) { // my template foo is not that strong. // but somthing like this. boost::mpl::for_each<typename XML_Traits<T>::Children,Serialize>(data); } template<> std::ostream& Serialize<XML_Empty>(T const&) { /* Do Nothing */ } My question is: Has anybody seen any projects/decumentation (not just XML) out there that uses techniques like this (template meta-programming) to emulate the concept of annotation used in languges like Java and C# that can then be used in code generation (to effectively automate the task by using a declaritive style). At this point in my research I am looking for more reading material and examples.

    Read the article

  • C two functions in one with casts

    - by Favolas
    I have two functions that do the exact same thing but in two different types of struct and this two types of struct are very similar. Imagine I have this two structs. typedef struct nodeOne{ Date *date; struct nodeOne *next; struct nodeOne *prev; }NodeOne; typedef struct nodeTwo{ Date *date; struct nodeTwo *next; struct nodeTwo *prev; }NodeTwo; Since my function to destroy each of the list is almost the same (Just the type of the arguments are different) I would like to make just one function to make the two thins. I have this two functions void destroyListOne(NodeOne **head, NodeOne **tail){ NodeOne *aux; while (*head != NULL){ aux = *head; *head = (*head)->next; free(aux); } *tail = NULL; } and this one: void destroyListTwo(NodeTwo **head, NodeTwo **tail){ NodeTwo *aux; while (*head != NULL){ aux = *head; *head = (*head)->next; free(aux); } *tail = NULL; } Since they are very similar I thought making something like this: void destroyList(void **ini, void **end, int listType){ if (listType == 0) { NodeOne *aux; NodeOne head = (NodeOne) ini; NodeOne tail = (NodeOne) ed; } else { NodeTwo *aux; NodeTwo head = (NodeTwo) ini; NodeTwo tail = (NodeTwo) ed; } while (*head != NULL){ aux = *head; *head = (*head)->next; free(aux); } *tail = NULL; } As you may now this is not working but I want to know if this is possible to achieve. I must maintain both of the structs as they are.

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >