Search Results

Search found 756 results on 31 pages for 'malloc'.

Page 16/31 | < Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >

  • hash table with chaining method program freezing

    - by Justin Carrey
    I am implementing hash table in C using linked list chaining method. The program compiles but when inserting a string in hash table, the program freezes and gets stuck. The program is below: struct llist{ char *s; struct llist *next; }; struct llist *a[100]; void hinsert(char *str){ int strint, hashinp; strint = 0; hashinp = 0; while(*str){ strint = strint+(*str); } hashinp = (strint%100); if(a[hashinp] == NULL){ struct llist *node; node = (struct llist *)malloc(sizeof(struct llist)); node->s = str; node->next = NULL; a[hashinp] = node; } else{ struct llist *node, *ptr; node = (struct llist *)malloc(sizeof(struct llist)); node->s = str; node->next = NULL; ptr = a[hashinp]; while(ptr->next != NULL){ ptr = ptr->next; } ptr->next = node; } } void hsearch(char *strsrch){ int strint1, hashinp1; strint1 = 0; hashinp1 = 0; while(*strsrch){ strint1 = strint1+(*strsrch); } hashinp1 = (strint1%100); struct llist *ptr1; ptr1 = a[hashinp1]; while(ptr1 != NULL){ if(ptr1->s == strsrch){ cout << "Element Found\n"; break; } else{ ptr1 = ptr1->next; } } if(ptr1 == NULL){ cout << "Element Not Found\n"; } } hinsert() is to insert elements into hash and hsearch is to search an element in the hash. Hash function is written inside hinsert() itself. In the main(), what i am initializing all the elements in a[] to be NULL like this: for(int i = 0;i < 100; i++){ a[i] = NULL; } Help is very much appreciated. Thanks !

    Read the article

  • making a queue program

    - by seventhief
    Hi can someone help me making a queue program. i want to set the array[0] to be array[1] just in display but in real i am adding value at array[0]. i got how to run the add function to it. but i can't do the view and delete command that will view from ex. array[0] to array[4], when displayed array[1] to array[5] with the value inserted. #include <stdio.h> #include <stdlib.h> #define p printf #define s scanf int rear = 0; int front = 0; int *q_array = NULL; int size = 0; main() { int num, opt; char cont[] = { 'y' }; clrscr(); p("Queue Program\n\n"); p("Queue size: "); s("%d", &size); p("\n"); if(size > 0) { q_array = malloc(size * sizeof(int)); if(q_array == NULL) { p("ERROR: malloc() failed\n"); exit(2); } } else { p("ERROR: size should be positive integer\n"); exit(1); } while((cont[0] == 'y') || (cont[0] == 'Y')) { clrscr(); p("Queue Program"); p("\n\nQueue size: %d\n\n", size); p("MAIN MENU\n1. Add\n2. Delete\n3. View"); p("\n\nYour choice: "); s("%d", &opt); p("\n"); switch(opt) { case 1: if(rear==size) { p("You can't add more data"); } else { p("Enter data for Queue[%d]: ", rear+1); s("%d", &num); add(num); } break; case 2: delt(); break; case 3: view(); break; } p("\n\nDo you want to continue? (Y\/N)"); s("%s", &cont[0]); } } add(int a) { q_array[rear]=a; rear++; } delt() { if(front==rear) { p("Queue Empty"); } else { p("Queue[%d] = %d removed.", front, q_array[front]); front++; } } view() { int i; for(i=front;i<=rear;i++) p("\nQueue[%d] = %d", i, q_array[i]); }

    Read the article

  • C/C++ variable length automatic array performance

    - by aaa
    hello. Is there significant cpu/memory overhead associated with using automatic arrays with g++/Intel on 64-bit x86 linux platform? int function(int N) { double array[N]; overhead compared to allocating array before hand (assuming function is called multiple times) overhead compared to using new overhead compared to using malloc range of N maybe from 1kb to 16kb roughly, stack overrun is not a problem Thank you

    Read the article

  • Segfault when iterating over a map<string, string> and drawing its contents using SDL_TTF

    - by Michael Stahre
    I'm not entirely sure this question belongs on gamedev.stackexchange, but I'm technically working on a game and working with SDL, so it might not be entirely offtopic. I've written a class called DebugText. The point of the class is to have a nice way of printing values of variables to the game screen. The idea is to call SetDebugText() with the variables in question every time they change or, as is currently the case, every time the game's Update() is called. The issue is that when iterating over the map that contains my variables and their latest updated values, I get segfaults. See the comments in DrawDebugText() below, it specifies where the error happens. I've tried splitting the calls to it-first and it-second into separate lines and found that the problem doesn't always happen when calling it-first. It alters between it-first and it-second. I can't find a pattern. It doesn't fail on every call to DrawDebugText() either. It might fail on the third time DrawDebugText() is called, or it might fail on the fourth. Class header: #ifndef CLIENT_DEBUGTEXT_H #define CLIENT_DEBUGTEXT_H #include <Map> #include <Math.h> #include <sstream> #include <SDL.h> #include <SDL_ttf.h> #include "vector2.h" using std::string; using std::stringstream; using std::map; using std::pair; using game::Vector2; namespace game { class DebugText { private: TTF_Font* debug_text_font; map<string, string>* debug_text_list; public: void SetDebugText(string var, bool value); void SetDebugText(string var, float value); void SetDebugText(string var, int value); void SetDebugText(string var, Vector2 value); void SetDebugText(string var, string value); int DrawDebugText(SDL_Surface*, SDL_Rect*); void InitDebugText(); void Clear(); }; } #endif Class source file: #include "debugtext.h" namespace game { // Copypasta function for handling the toString conversion template <class T> inline string to_string (const T& t) { stringstream ss (stringstream::in | stringstream::out); ss << t; return ss.str(); } // Initializes SDL_TTF and sets its font void DebugText::InitDebugText() { if(TTF_WasInit()) TTF_Quit(); TTF_Init(); debug_text_font = TTF_OpenFont("LiberationSans-Regular.ttf", 16); TTF_SetFontStyle(debug_text_font, TTF_STYLE_NORMAL); } // Iterates over the current debug_text_list and draws every element on the screen. // After drawing with SDL you need to get a rect specifying the area on the screen that was changed and tell SDL that this part of the screen needs to be updated. this is done in the game's Draw() function // This function sets rects_to_update to the new list of rects provided by all of the surfaces and returns the number of rects in the list. These two parameters are used in Draw() when calling on SDL_UpdateRects(), which takes an SDL_Rect* and a list length int DebugText::DrawDebugText(SDL_Surface* screen, SDL_Rect* rects_to_update) { if(debug_text_list == NULL) return 0; if(!TTF_WasInit()) InitDebugText(); rects_to_update = NULL; // Specifying the font color SDL_Color font_color = {0xff, 0x00, 0x00, 0x00}; // r, g, b, unused int row_count = 0; string line; // The iterator variable map<string, string>::iterator it; // Gets the iterator and iterates over it for(it = debug_text_list->begin(); it != debug_text_list->end(); it++) { // Takes the first value (the name of the variable) and the second value (the value of the parameter in string form) //---------THIS LINE GIVES ME SEGFAULTS----- line = it->first + ": " + it->second; //------------------------------------------ // Creates a surface with the text on it that in turn can be rendered to the screen itself later SDL_Surface* debug_surface = TTF_RenderText_Solid(debug_text_font, line.c_str(), font_color); if(debug_surface == NULL) { // A standard check for errors fprintf(stderr, "Error: %s", TTF_GetError()); return NULL; } else { // If SDL_TTF did its job right, then we now set a destination rect row_count++; SDL_Rect dstrect = {5, 5, 0, 0}; // x, y, w, h dstrect.x = 20; dstrect.y = 20*row_count; // Draws the surface with the text on it to the screen int res = SDL_BlitSurface(debug_surface,NULL,screen,&dstrect); if(res != 0) { //Just an error check fprintf(stderr, "Error: %s", SDL_GetError()); return NULL; } // Creates a new rect to specify the area that needs to be updated with SDL_Rect* new_rect_to_update = (SDL_Rect*) malloc(sizeof(SDL_Rect)); new_rect_to_update->h = debug_surface->h; new_rect_to_update->w = debug_surface->w; new_rect_to_update->x = dstrect.x; new_rect_to_update->y = dstrect.y; // Just freeing the surface since it isn't necessary anymore SDL_FreeSurface(debug_surface); // Creates a new list of rects with room for the new rect SDL_Rect* newtemp = (SDL_Rect*) malloc(row_count*sizeof(SDL_Rect)); // Copies the data from the old list of rects to the new one memcpy(newtemp, rects_to_update, (row_count-1)*sizeof(SDL_Rect)); // Adds the new rect to the new list newtemp[row_count-1] = *new_rect_to_update; // Frees the memory used by the old list free(rects_to_update); // And finally redirects the pointer to the old list to the new list rects_to_update = newtemp; newtemp = NULL; } } // When the entire map has been iterated over, return the number of lines that were drawn, ie. the number of rects in the returned rect list return row_count; } // The SetDebugText used by all the SetDebugText overloads // Takes two strings, inserts them into the map as a pair void DebugText::SetDebugText(string var, string value) { if (debug_text_list == NULL) { debug_text_list = new map<string, string>(); } debug_text_list->erase(var); debug_text_list->insert(pair<string, string>(var, value)); } // Writes the bool to a string and calls SetDebugText(string, string) void DebugText::SetDebugText(string var, bool value) { string result; if (value) result = "True"; else result = "False"; SetDebugText(var, result); } // Does the same thing, but uses to_string() to convert the float void DebugText::SetDebugText(string var, float value) { SetDebugText(var, to_string(value)); } // Same as above, but int void DebugText::SetDebugText(string var, int value) { SetDebugText(var, to_string(value)); } // Vector2 is a struct of my own making. It contains the two float vars x and y void DebugText::SetDebugText(string var, Vector2 value) { SetDebugText(var + ".x", to_string(value.x)); SetDebugText(var + ".y", to_string(value.y)); } // Empties the list. I don't actually use this in my code. Shame on me for writing something I don't use. void DebugText::Clear() { if(debug_text_list != NULL) debug_text_list->clear(); } }

    Read the article

  • Different Not Automatically Implies Better

    - by Alois Kraus
    Originally posted on: http://geekswithblogs.net/akraus1/archive/2013/11/05/154556.aspxRecently I was digging deeper why some WCF hosted workflow application did consume quite a lot of memory although it did basically only load a xaml workflow. The first tool of choice is Process Explorer or even better Process Hacker (has more options and the best feature copy&paste does work). The three most important numbers of a process with regards to memory are Working Set, Private Working Set and Private Bytes. Working set is the currently consumed physical memory (parts can be shared between processes e.g. loaded dlls which are read only) Private Working Set is the physical memory needed by this process which is not shareable Private Bytes is the number of non shareable which is only visible in the current process (e.g. all new, malloc, VirtualAlloc calls do create private bytes) When you have a bigger workflow it can consume under 64 bit easily 500MB for a 1-2 MB xaml file. This does not look very scalable. Under 64 bit the issue is excessive private bytes consumption and not the managed heap. The picture is quite different for 32 bit which looks a bit strange but it seems that the hosted VB compiler is a lot less memory hungry under 32 bit. I did try to repro the issue with a medium sized xaml file (400KB) which does contain 1000 variables and 1000 if which can be represented by C# code like this: string Var1; string Var2; ... string Var1000; if (!String.IsNullOrEmpty(Var1) ) { Console.WriteLine(“Var1”); } if (!String.IsNullOrEmpty(Var2) ) { Console.WriteLine(“Var2”); } ....   Since WF is based on VB.NET expressions you are bound to the hosted VB.NET compiler which does result in (x64) 140 MB of private bytes which is ca. 140 KB for each if clause which is quite a lot if you think about the actually present functionality. But there is hope. .NET 4.5 does allow now C# expressions for WF which is a major step forward for all C# lovers. I did create some simple patcher to “cross compile” my xaml to C# expressions. Lets look at the result: C# Expressions VB Expressions x86 x86 On my home machine I have only 32 bit which gives you quite exactly half of the memory consumption under 64 bit. C# expressions are 10 times more memory hungry than VB.NET expressions! I wanted to do more with less memory but instead it did consume a magnitude more memory. That is surprising to say the least. The workflow does initialize in about the same time under x64 and x86 where the VB code does it in 2s whereas the C# version needs 18s. Also nearly ten times slower. That is a too high price to pay for any bigger sized xaml workflow to convert from VB.NET to C# expressions. If I do reduce the number of expressions to 500 then it does need 400MB which is about half of the memory. It seems that the cost per if does rise linear with the number of total expressions in a xaml workflow.  Expression Language Cost per IF Startup Time C# 1000 Ifs x64 1,5 MB 18s C# 500 Ifs x64 750 KB 9s VB 1000 Ifs x64 140 KB 2s VB 500 Ifs x64 70 KB 1s Now we can directly compare two MS implementations. It is clear that the VB.NET compiler uses the same underlying structure but it has much higher offset compared to the highly inefficient C# expression compiler. I have filed a connect bug here with a harsher wording about recent advances in memory consumption. The funniest thing is that one MS employee did give an Azure AppFabric demo around early 2011 which was so slow that he needed to investigate with xperf. He was after startup time and the call stacks with regards to VB.NET expression compilation were remarkably similar. In fact I only found this post by googling for parts of my call stacks. … “C# expressions will be coming soon to WF, and that will have different performance characteristics than VB” … What did he know Jan 2011 what I did no know until today? ;-). He knew that C# expression will come but that they will not be automatically have better footprint. It is about time to fix that. In its current state C# expressions are not usable for bigger workflows. That also explains the headline for today. You can cheat startup time by prestarting workflows so that the demo looks nice and snappy but it does hurt scalability a lot since you do need much more memory than necessary. I did find the stacks by enabling virtual allocation tracking within XPerf which is still the best tool out there. But first you need to look at your process to check where the memory is hiding: For the C# Expression compiler you do not need xperf. You can directly dump the managed heap and check with a profiler of your choice. But if the allocations are happening on the Private Data ( VirtualAlloc ) you can find it with xperf. There is a nice video on channel 9 explaining VirtualAlloc tracking it in greater detail. If your data allocations are on the Heap it does mean that the C/C++ runtime did create a heap for you where all malloc, new calls do allocate from it. You can enable heap tracing with xperf and full call stack support as well which is doable via xperf like it is shown also on channel 9. Or you can use WPRUI directly: To make “Heap Usage” it work you need to set for your executable the tracing flags (before you start it). For example devenv.exe HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\devenv.exe DWORD TracingFlags 1 Do not forget to disable it after you did complete profiling the process or it will impact the startup time quite a lot. You can with xperf attach directly to a running process and collect heap allocation information from a gone wild process. Very handy if you need to find out what a process was doing which has arrived in a funny state. “VirtualAlloc usage” does work without explicitly enabling stuff for a specific process and is always on machine wide. I had issues on my Windows 7 machines with the call stack collection and the latest Windows 8.1 Performance Toolkit. I was told that WPA from Windows 8.0 should work fine but I do not want to downgrade.

    Read the article

  • Error in running script [closed]

    - by SWEngineer
    I'm trying to run heathusf_v1.1.0.tar.gz found here I installed tcsh to make build_heathusf work. But, when I run ./build_heathusf, I get the following (I'm running that on a Fedora Linux system from Terminal): $ ./build_heathusf Compiling programs to build a library of image processing functions. convexpolyscan.c: In function ‘cdelete’: convexpolyscan.c:346:5: warning: incompatible implicit declaration of built-in function ‘bcopy’ [enabled by default] myalloc.c: In function ‘mycalloc’: myalloc.c:68:16: error: invalid storage class for function ‘store_link’ myalloc.c: In function ‘mymalloc’: myalloc.c:101:16: error: invalid storage class for function ‘store_link’ myalloc.c: In function ‘myfree’: myalloc.c:129:27: error: invalid storage class for function ‘find_link’ myalloc.c:131:12: warning: assignment makes pointer from integer without a cast [enabled by default] myalloc.c: At top level: myalloc.c:150:13: warning: conflicting types for ‘store_link’ [enabled by default] myalloc.c:150:13: error: static declaration of ‘store_link’ follows non-static declaration myalloc.c:91:4: note: previous implicit declaration of ‘store_link’ was here myalloc.c:164:24: error: conflicting types for ‘find_link’ myalloc.c:131:14: note: previous implicit declaration of ‘find_link’ was here Building the mammogram resizing program. gcc -O2 -I. -I../common mkimage.o -o mkimage -L../common -lmammo -lm ../common/libmammo.a(aggregate.o): In function `aggregate': aggregate.c:(.text+0x7fa): undefined reference to `mycalloc' aggregate.c:(.text+0x81c): undefined reference to `mycalloc' aggregate.c:(.text+0x868): undefined reference to `mycalloc' ../common/libmammo.a(aggregate.o): In function `aggregate_median': aggregate.c:(.text+0xbc5): undefined reference to `mymalloc' aggregate.c:(.text+0xbfb): undefined reference to `mycalloc' aggregate.c:(.text+0xc3c): undefined reference to `mycalloc' ../common/libmammo.a(aggregate.o): In function `aggregate': aggregate.c:(.text+0x9b5): undefined reference to `myfree' ../common/libmammo.a(aggregate.o): In function `aggregate_median': aggregate.c:(.text+0xd85): undefined reference to `myfree' ../common/libmammo.a(optical_density.o): In function `linear_optical_density': optical_density.c:(.text+0x29e): undefined reference to `mymalloc' optical_density.c:(.text+0x342): undefined reference to `mycalloc' optical_density.c:(.text+0x383): undefined reference to `mycalloc' ../common/libmammo.a(optical_density.o): In function `log10_optical_density': optical_density.c:(.text+0x693): undefined reference to `mymalloc' optical_density.c:(.text+0x74f): undefined reference to `mycalloc' optical_density.c:(.text+0x790): undefined reference to `mycalloc' ../common/libmammo.a(optical_density.o): In function `map_with_ushort_lut': optical_density.c:(.text+0xb2e): undefined reference to `mymalloc' optical_density.c:(.text+0xb87): undefined reference to `mycalloc' optical_density.c:(.text+0xbc6): undefined reference to `mycalloc' ../common/libmammo.a(optical_density.o): In function `linear_optical_density': optical_density.c:(.text+0x4d9): undefined reference to `myfree' ../common/libmammo.a(optical_density.o): In function `log10_optical_density': optical_density.c:(.text+0x8f1): undefined reference to `myfree' ../common/libmammo.a(optical_density.o): In function `map_with_ushort_lut': optical_density.c:(.text+0xd0d): undefined reference to `myfree' ../common/libmammo.a(virtual_image.o): In function `deallocate_cached_image': virtual_image.c:(.text+0x3dc6): undefined reference to `myfree' virtual_image.c:(.text+0x3dd7): undefined reference to `myfree' ../common/libmammo.a(virtual_image.o):virtual_image.c:(.text+0x3de5): more undefined references to `myfree' follow ../common/libmammo.a(virtual_image.o): In function `allocate_cached_image': virtual_image.c:(.text+0x4233): undefined reference to `mycalloc' virtual_image.c:(.text+0x4253): undefined reference to `mymalloc' virtual_image.c:(.text+0x4275): undefined reference to `mycalloc' virtual_image.c:(.text+0x42e7): undefined reference to `mycalloc' virtual_image.c:(.text+0x44f9): undefined reference to `mycalloc' virtual_image.c:(.text+0x47a9): undefined reference to `mycalloc' virtual_image.c:(.text+0x4a45): undefined reference to `mycalloc' virtual_image.c:(.text+0x4af4): undefined reference to `myfree' collect2: error: ld returned 1 exit status make: *** [mkimage] Error 1 Building the breast segmentation program. gcc -O2 -I. -I../common breastsegment.o segment.o -o breastsegment -L../common -lmammo -lm breastsegment.o: In function `render_segmentation_sketch': breastsegment.c:(.text+0x43): undefined reference to `mycalloc' breastsegment.c:(.text+0x58): undefined reference to `mycalloc' breastsegment.c:(.text+0x12f): undefined reference to `mycalloc' breastsegment.c:(.text+0x1b9): undefined reference to `myfree' breastsegment.c:(.text+0x1c6): undefined reference to `myfree' breastsegment.c:(.text+0x1e1): undefined reference to `myfree' segment.o: In function `find_center': segment.c:(.text+0x53): undefined reference to `mycalloc' segment.c:(.text+0x71): undefined reference to `mycalloc' segment.c:(.text+0x387): undefined reference to `myfree' segment.o: In function `bordercode': segment.c:(.text+0x4ac): undefined reference to `mycalloc' segment.c:(.text+0x546): undefined reference to `mycalloc' segment.c:(.text+0x651): undefined reference to `mycalloc' segment.c:(.text+0x691): undefined reference to `myfree' segment.o: In function `estimate_tissue_image': segment.c:(.text+0x10d4): undefined reference to `mycalloc' segment.c:(.text+0x14da): undefined reference to `mycalloc' segment.c:(.text+0x1698): undefined reference to `mycalloc' segment.c:(.text+0x1834): undefined reference to `mycalloc' segment.c:(.text+0x1850): undefined reference to `mycalloc' segment.o:segment.c:(.text+0x186a): more undefined references to `mycalloc' follow segment.o: In function `estimate_tissue_image': segment.c:(.text+0x1bbc): undefined reference to `myfree' segment.c:(.text+0x1c4a): undefined reference to `mycalloc' segment.c:(.text+0x1c7c): undefined reference to `mycalloc' segment.c:(.text+0x1d8e): undefined reference to `myfree' segment.c:(.text+0x1d9b): undefined reference to `myfree' segment.c:(.text+0x1da8): undefined reference to `myfree' segment.c:(.text+0x1dba): undefined reference to `myfree' segment.c:(.text+0x1dc9): undefined reference to `myfree' segment.o:segment.c:(.text+0x1dd8): more undefined references to `myfree' follow segment.o: In function `estimate_tissue_image': segment.c:(.text+0x20bf): undefined reference to `mycalloc' segment.o: In function `segment_breast': segment.c:(.text+0x24cd): undefined reference to `mycalloc' segment.o: In function `find_center': segment.c:(.text+0x3a4): undefined reference to `myfree' segment.o: In function `bordercode': segment.c:(.text+0x6ac): undefined reference to `myfree' ../common/libmammo.a(aggregate.o): In function `aggregate': aggregate.c:(.text+0x7fa): undefined reference to `mycalloc' aggregate.c:(.text+0x81c): undefined reference to `mycalloc' aggregate.c:(.text+0x868): undefined reference to `mycalloc' ../common/libmammo.a(aggregate.o): In function `aggregate_median': aggregate.c:(.text+0xbc5): undefined reference to `mymalloc' aggregate.c:(.text+0xbfb): undefined reference to `mycalloc' aggregate.c:(.text+0xc3c): undefined reference to `mycalloc' ../common/libmammo.a(aggregate.o): In function `aggregate': aggregate.c:(.text+0x9b5): undefined reference to `myfree' ../common/libmammo.a(aggregate.o): In function `aggregate_median': aggregate.c:(.text+0xd85): undefined reference to `myfree' ../common/libmammo.a(cc_label.o): In function `cc_label': cc_label.c:(.text+0x20c): undefined reference to `mycalloc' cc_label.c:(.text+0x6c2): undefined reference to `mycalloc' cc_label.c:(.text+0xbaa): undefined reference to `myfree' ../common/libmammo.a(cc_label.o): In function `cc_label_0bkgd': cc_label.c:(.text+0xe17): undefined reference to `mycalloc' cc_label.c:(.text+0x12d7): undefined reference to `mycalloc' cc_label.c:(.text+0x17e7): undefined reference to `myfree' ../common/libmammo.a(cc_label.o): In function `cc_relabel_by_intensity': cc_label.c:(.text+0x18c5): undefined reference to `mycalloc' ../common/libmammo.a(cc_label.o): In function `cc_label_4connect': cc_label.c:(.text+0x1cf0): undefined reference to `mycalloc' cc_label.c:(.text+0x2195): undefined reference to `mycalloc' cc_label.c:(.text+0x26a4): undefined reference to `myfree' ../common/libmammo.a(cc_label.o): In function `cc_relabel_by_intensity': cc_label.c:(.text+0x1b06): undefined reference to `myfree' ../common/libmammo.a(convexpolyscan.o): In function `polyscan_coords': convexpolyscan.c:(.text+0x6f0): undefined reference to `mycalloc' convexpolyscan.c:(.text+0x75f): undefined reference to `mycalloc' convexpolyscan.c:(.text+0x7ab): undefined reference to `myfree' convexpolyscan.c:(.text+0x7b8): undefined reference to `myfree' ../common/libmammo.a(convexpolyscan.o): In function `polyscan_poly_cacheim': convexpolyscan.c:(.text+0x805): undefined reference to `mycalloc' convexpolyscan.c:(.text+0x894): undefined reference to `myfree' ../common/libmammo.a(mikesfileio.o): In function `read_segmentation_file': mikesfileio.c:(.text+0x1e9): undefined reference to `mycalloc' mikesfileio.c:(.text+0x205): undefined reference to `mycalloc' ../common/libmammo.a(optical_density.o): In function `linear_optical_density': optical_density.c:(.text+0x29e): undefined reference to `mymalloc' optical_density.c:(.text+0x342): undefined reference to `mycalloc' optical_density.c:(.text+0x383): undefined reference to `mycalloc' ../common/libmammo.a(optical_density.o): In function `log10_optical_density': optical_density.c:(.text+0x693): undefined reference to `mymalloc' optical_density.c:(.text+0x74f): undefined reference to `mycalloc' optical_density.c:(.text+0x790): undefined reference to `mycalloc' ../common/libmammo.a(optical_density.o): In function `map_with_ushort_lut': optical_density.c:(.text+0xb2e): undefined reference to `mymalloc' optical_density.c:(.text+0xb87): undefined reference to `mycalloc' optical_density.c:(.text+0xbc6): undefined reference to `mycalloc' ../common/libmammo.a(optical_density.o): In function `linear_optical_density': optical_density.c:(.text+0x4d9): undefined reference to `myfree' ../common/libmammo.a(optical_density.o): In function `log10_optical_density': optical_density.c:(.text+0x8f1): undefined reference to `myfree' ../common/libmammo.a(optical_density.o): In function `map_with_ushort_lut': optical_density.c:(.text+0xd0d): undefined reference to `myfree' ../common/libmammo.a(virtual_image.o): In function `deallocate_cached_image': virtual_image.c:(.text+0x3dc6): undefined reference to `myfree' virtual_image.c:(.text+0x3dd7): undefined reference to `myfree' ../common/libmammo.a(virtual_image.o):virtual_image.c:(.text+0x3de5): more undefined references to `myfree' follow ../common/libmammo.a(virtual_image.o): In function `allocate_cached_image': virtual_image.c:(.text+0x4233): undefined reference to `mycalloc' virtual_image.c:(.text+0x4253): undefined reference to `mymalloc' virtual_image.c:(.text+0x4275): undefined reference to `mycalloc' virtual_image.c:(.text+0x42e7): undefined reference to `mycalloc' virtual_image.c:(.text+0x44f9): undefined reference to `mycalloc' virtual_image.c:(.text+0x47a9): undefined reference to `mycalloc' virtual_image.c:(.text+0x4a45): undefined reference to `mycalloc' virtual_image.c:(.text+0x4af4): undefined reference to `myfree' collect2: error: ld returned 1 exit status make: *** [breastsegment] Error 1 Building the mass feature generation program. gcc -O2 -I. -I../common afumfeature.o -o afumfeature -L../common -lmammo -lm afumfeature.o: In function `afum_process': afumfeature.c:(.text+0xd80): undefined reference to `mycalloc' afumfeature.c:(.text+0xd9c): undefined reference to `mycalloc' afumfeature.c:(.text+0xe80): undefined reference to `mycalloc' afumfeature.c:(.text+0x11f8): undefined reference to `myfree' afumfeature.c:(.text+0x1207): undefined reference to `myfree' afumfeature.c:(.text+0x1214): undefined reference to `myfree' ../common/libmammo.a(aggregate.o): In function `aggregate': aggregate.c:(.text+0x7fa): undefined reference to `mycalloc' aggregate.c:(.text+0x81c): undefined reference to `mycalloc' aggregate.c:(.text+0x868): undefined reference to `mycalloc' ../common/libmammo.a(aggregate.o): In function `aggregate_median': aggregate.c:(.text+0xbc5): undefined reference to `mymalloc' aggregate.c:(.text+0xbfb): undefined reference to `mycalloc' aggregate.c:(.text+0xc3c): undefined reference to `mycalloc' ../common/libmammo.a(aggregate.o): In function `aggregate': aggregate.c:(.text+0x9b5): undefined reference to `myfree' ../common/libmammo.a(aggregate.o): In function `aggregate_median': aggregate.c:(.text+0xd85): undefined reference to `myfree' ../common/libmammo.a(convexpolyscan.o): In function `polyscan_coords': convexpolyscan.c:(.text+0x6f0): undefined reference to `mycalloc' convexpolyscan.c:(.text+0x75f): undefined reference to `mycalloc' convexpolyscan.c:(.text+0x7ab): undefined reference to `myfree' convexpolyscan.c:(.text+0x7b8): undefined reference to `myfree' ../common/libmammo.a(convexpolyscan.o): In function `polyscan_poly_cacheim': convexpolyscan.c:(.text+0x805): undefined reference to `mycalloc' convexpolyscan.c:(.text+0x894): undefined reference to `myfree' ../common/libmammo.a(mikesfileio.o): In function `read_segmentation_file': mikesfileio.c:(.text+0x1e9): undefined reference to `mycalloc' mikesfileio.c:(.text+0x205): undefined reference to `mycalloc' ../common/libmammo.a(optical_density.o): In function `linear_optical_density': optical_density.c:(.text+0x29e): undefined reference to `mymalloc' optical_density.c:(.text+0x342): undefined reference to `mycalloc' optical_density.c:(.text+0x383): undefined reference to `mycalloc' ../common/libmammo.a(optical_density.o): In function `log10_optical_density': optical_density.c:(.text+0x693): undefined reference to `mymalloc' optical_density.c:(.text+0x74f): undefined reference to `mycalloc' optical_density.c:(.text+0x790): undefined reference to `mycalloc' ../common/libmammo.a(optical_density.o): In function `map_with_ushort_lut': optical_density.c:(.text+0xb2e): undefined reference to `mymalloc' optical_density.c:(.text+0xb87): undefined reference to `mycalloc' optical_density.c:(.text+0xbc6): undefined reference to `mycalloc' ../common/libmammo.a(optical_density.o): In function `linear_optical_density': optical_density.c:(.text+0x4d9): undefined reference to `myfree' ../common/libmammo.a(optical_density.o): In function `log10_optical_density': optical_density.c:(.text+0x8f1): undefined reference to `myfree' ../common/libmammo.a(optical_density.o): In function `map_with_ushort_lut': optical_density.c:(.text+0xd0d): undefined reference to `myfree' ../common/libmammo.a(virtual_image.o): In function `deallocate_cached_image': virtual_image.c:(.text+0x3dc6): undefined reference to `myfree' virtual_image.c:(.text+0x3dd7): undefined reference to `myfree' ../common/libmammo.a(virtual_image.o):virtual_image.c:(.text+0x3de5): more undefined references to `myfree' follow ../common/libmammo.a(virtual_image.o): In function `allocate_cached_image': virtual_image.c:(.text+0x4233): undefined reference to `mycalloc' virtual_image.c:(.text+0x4253): undefined reference to `mymalloc' virtual_image.c:(.text+0x4275): undefined reference to `mycalloc' virtual_image.c:(.text+0x42e7): undefined reference to `mycalloc' virtual_image.c:(.text+0x44f9): undefined reference to `mycalloc' virtual_image.c:(.text+0x47a9): undefined reference to `mycalloc' virtual_image.c:(.text+0x4a45): undefined reference to `mycalloc' virtual_image.c:(.text+0x4af4): undefined reference to `myfree' collect2: error: ld returned 1 exit status make: *** [afumfeature] Error 1 Building the mass detection program. make: Nothing to be done for `all'. Building the performance evaluation program. gcc -O2 -I. -I../common DDSMeval.o polyscan.o -o DDSMeval -L../common -lmammo -lm ../common/libmammo.a(mikesfileio.o): In function `read_segmentation_file': mikesfileio.c:(.text+0x1e9): undefined reference to `mycalloc' mikesfileio.c:(.text+0x205): undefined reference to `mycalloc' collect2: error: ld returned 1 exit status make: *** [DDSMeval] Error 1 Building the template creation program. gcc -O2 -I. -I../common mktemplate.o polyscan.o -o mktemplate -L../common -lmammo -lm Building the drawimage program. gcc -O2 -I. -I../common drawimage.o -o drawimage -L../common -lmammo -lm ../common/libmammo.a(mikesfileio.o): In function `read_segmentation_file': mikesfileio.c:(.text+0x1e9): undefined reference to `mycalloc' mikesfileio.c:(.text+0x205): undefined reference to `mycalloc' collect2: error: ld returned 1 exit status make: *** [drawimage] Error 1 Building the compression/decompression program jpeg. gcc -O2 -DSYSV -DNOTRUNCATE -c lexer.c lexer.c:41:1: error: initializer element is not constant lexer.c:41:1: error: (near initialization for ‘yyin’) lexer.c:41:1: error: initializer element is not constant lexer.c:41:1: error: (near initialization for ‘yyout’) lexer.c: In function ‘initparser’: lexer.c:387:21: warning: incompatible implicit declaration of built-in function ‘strlen’ [enabled by default] lexer.c: In function ‘MakeLink’: lexer.c:443:16: warning: incompatible implicit declaration of built-in function ‘malloc’ [enabled by default] lexer.c:447:7: warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default] lexer.c:452:7: warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default] lexer.c:455:34: warning: incompatible implicit declaration of built-in function ‘calloc’ [enabled by default] lexer.c:458:7: warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default] lexer.c:460:3: warning: incompatible implicit declaration of built-in function ‘strcpy’ [enabled by default] lexer.c: In function ‘getstr’: lexer.c:548:26: warning: incompatible implicit declaration of built-in function ‘malloc’ [enabled by default] lexer.c:552:4: warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default] lexer.c:557:21: warning: incompatible implicit declaration of built-in function ‘calloc’ [enabled by default] lexer.c:557:28: warning: incompatible implicit declaration of built-in function ‘strlen’ [enabled by default] lexer.c:561:7: warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default] lexer.c: In function ‘parser’: lexer.c:794:21: warning: incompatible implicit declaration of built-in function ‘calloc’ [enabled by default] lexer.c:798:8: warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default] lexer.c:1074:21: warning: incompatible implicit declaration of built-in function ‘calloc’ [enabled by default] lexer.c:1078:8: warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default] lexer.c:1116:21: warning: incompatible implicit declaration of built-in function ‘calloc’ [enabled by default] lexer.c:1120:8: warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default] lexer.c:1154:25: warning: incompatible implicit declaration of built-in function ‘calloc’ [enabled by default] lexer.c:1158:5: warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default] lexer.c:1190:5: warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default] lexer.c:1247:25: warning: incompatible implicit declaration of built-in function ‘calloc’ [enabled by default] lexer.c:1251:5: warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default] lexer.c:1283:5: warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default] lexer.c: In function ‘yylook’: lexer.c:1867:9: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast] lexer.c:1867:20: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast] lexer.c:1877:12: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast] lexer.c:1877:23: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast] make: *** [lexer.o] Error 1

    Read the article

  • Varnish Error 503 Service Unavailable

    - by alfish
    On Debian I have Varnish cache in front of apache and get 503 error when I try to get urls which are rarely fetched. I've put 10 min timeout in default.vlc: backend default { .host = "127.0.0.1"; .port = "81"; .connect_timeout = 600s; .first_byte_timeout = 600s; .between_bytes_timeout = 600s; } Also I have in /etc/default/varnish DAEMON_OPTS="-a :80 \ -T localhost:6082 \ -b localhost:81 \ -u varnish -g varnish \ -S /etc/varnish/secret \ -p thread_pools=7 \ -p thread_pool_min=200 \ -p thread_pool_max=5000 \ -p listen_depth=2048 \ -p thread_pool_add_delay=2\ -p lru_interval=1800 \ -h classic,169313 \ -p session_linger=100 \ -p sess_workspace=262144 \ -p connect_timeout=600 \ -p max_restarts=6 \ -s malloc,7G" I appreciate your hints to resove this problem.

    Read the article

  • Changing memory allocator to Jemalloc Centos 6

    - by Brian Lovett
    After reading this blog post about the impact of memory allocators like jemalloc on highly threaded applications, I wanted to test things on a larger scale on some of our cluster of servers. We run sphinx, and apache using threads, and on 24 core machines. Installing jemalloc was simple enough. We are running Centos 6, so yum install jemalloc jemalloc-devel did the trick. My question is, how do we change everything on the system over to using jemalloc instead of the default malloc built into Centos. Research pointed me at this as a potential option: LD_PRELOAD=$LD_PRELOAD:/usr/lib64/libjemalloc.so.1 Would this be sufficient to get everything using jemalloc?

    Read the article

  • How can I improve my error checking and handling?

    - by Google
    Lately I have been struggling to understand what the right amount of checking is and what the proper methods are. I have a few questions regarding this: What is the proper way to check for errors (bad input, bad states, etc)? Is it better to explicitly check for errors, or use functions like asserts which can be optimized out of your final code? I feel like explicitly checking clutters a program with a lot of extra code which shouldn't be executed in most situations anyway-- and not to mention most errors end up with an abort/exit failure. Why clutter a function with explicit checks just to abort? I have looked for asserts versus explicit checking of errors and found little to truly explain when to do either. Most say 'use asserts to check for logic errors and use explicit checks to check for other failures.' This doesn't seem to get us very far though. Would we say this is feasible: Malloc returning null, check explictly API user inserting odd input for functions, use asserts Would this make me any better at error checking? What else can I do? I really want to improve and write better, 'professional' code.

    Read the article

  • Varnish VCL not allowing two separate IP addresses as backends

    - by Peter Griffin
    Every time I attempt to add an extra back end into our VCL file, it's fails. Here is the DAEMON_OPTS we are running off: DAEMON_OPTS="-a :80 \ -T localhost:6082 \ -f /etc/varnish/custom.vcl \ -u varnish -g varnish \ -S /etc/varnish/secret \ -s malloc,10G" And here is the offending backend(s) backend default { .host = "114.123.456.789"; .port = "8080"; } backend alt { .host = "203.123.456.789"; .port = "80"; } Any Ideas ? Gut feeling is it might need the backends to be set somewhere, but I'm not sure where.

    Read the article

  • Unable to list contents/remove directory (linux ext3)

    - by RedKrieg
    System is CentOS5 x86_64, completely up to date. I've got a folder that can't be listed (ls just hangs, eating memory until it is killed). The directory size is nearly 500k: root@server [/home/user/public_html/domain.com/wp-content/uploads/2010/03]# stat . File: `.' Size: 458752 Blocks: 904 IO Block: 4096 directory Device: 812h/2066d Inode: 44499071 Links: 2 Access: (0755/drwxr-xr-x) Uid: ( 3292/ user) Gid: ( 3287/ user) Access: 2012-06-29 17:31:47.000000000 -0400 Modify: 2012-10-23 14:41:58.000000000 -0400 Change: 2012-10-23 14:41:58.000000000 -0400 I can see the file names if I use ls -1f, but it just repeats the same 48 files ad infinitum, all of which have non-ascii characters somewhere in the file name: La-critic\363-al-servicio-la-privacidad-300x160.jpg When I try to access the files (say to copy them or remove them) I get messages like the following: lstat("/home/user/public_html/domain.com/wp-content/uploads/2010/03/Sebast\355an-Pi\361era-el-balc\363n-150x120.jpg", 0x7fff364c52c0) = -1 ENOENT (No such file or directory) I tried altering the code found on this man page and modified the code to call unlink for each file. I get the same ENOENT error from the unlink call: unlink("/home/user/public_html/domain.com/wp-content/uploads/2010/03/Marca-naci\363n-Madrid-150x120.jpg") = -1 ENOENT (No such file or directory) I also straced a "touch", grabbed the syscalls it makes and replicated them, then tried to unlink the resulting file by name. This works fine, but the folder still contains an entry by the same name after the operation completes and the program runs for an arbitrarily long time (strace output ended up at 20GB after 5 minutes and I stopped the process). I'm stumped on this one, I'd really prefer not to have to take this production machine (hundreds of customers) offline to fsck the filesystem, but I'm leaning toward that being the only option at this point. If anyone's had success using other methods for removing files (by inode number, I can get those with the getdents code) I'd love to hear them. (Yes, I've tried find . -inum <inode> -exec rm -fv {} \; and it still has the problem with unlink returning ENOENT) For those interested, here's the diff between that man page's code and mine. I didn't bother with error checking on mallocs, etc because I'm lazy and this is a one-off: root@server [~]# diff -u listdir-orig.c listdir.c --- listdir-orig.c 2012-10-23 15:10:02.000000000 -0400 +++ listdir.c 2012-10-23 14:59:47.000000000 -0400 @@ -6,6 +6,7 @@ #include <stdlib.h> #include <sys/stat.h> #include <sys/syscall.h> +#include <string.h> #define handle_error(msg) \ do { perror(msg); exit(EXIT_FAILURE); } while (0) @@ -17,7 +18,7 @@ char d_name[]; }; -#define BUF_SIZE 1024 +#define BUF_SIZE 1024*1024*5 int main(int argc, char *argv[]) { @@ -26,11 +27,16 @@ struct linux_dirent *d; int bpos; char d_type; + int deleted; + int file_descriptor; fd = open(argc > 1 ? argv[1] : ".", O_RDONLY | O_DIRECTORY); if (fd == -1) handle_error("open"); + char* full_path; + char* fd_path; + for ( ; ; ) { nread = syscall(SYS_getdents, fd, buf, BUF_SIZE); if (nread == -1) @@ -55,7 +61,24 @@ printf("%4d %10lld %s\n", d->d_reclen, (long long) d->d_off, (char *) d->d_name); bpos += d->d_reclen; + if ( d_type == DT_REG ) + { + full_path = malloc(strlen((char *) d->d_name) + strlen(argv[1]) + 2); //One for the /, one for the \0 + strcpy(full_path, argv[1]); + strcat(full_path, (char *) d->d_name); + + //We're going to try to "touch" the file. + //file_descriptor = open(full_path, O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK, 0666); + //fd_path = malloc(32); //Lazy, only really needs 16 + //sprintf(fd_path, "/proc/self/fd/%d", file_descriptor); + //utimes(fd_path, NULL); + //close(file_descriptor); + deleted = unlink(full_path); + if ( deleted == -1 ) printf("Error unlinking file\n"); + break; //Break on first try + } } + break; //Break on first try } exit(EXIT_SUCCESS);

    Read the article

  • Encapsulate standard C functions?

    - by Jack Stout
    While studying the C programming language and learning safe practices, I'm inclined to write a layer of functionality over several parts of the standard library. This would serve two purposes: I could use standard parts of the language in ways that feel more familiar or rational to me, and I could easily replace that functionality with my own, if I needed to. I could benefit from this, but should I do it? As an example, we can consider memory management. If I've written malloc() into the constructors of each of my objects, then decide that I need to handle memory allocation on my own, I have to edit the constructor associated with every object. By referencing my own function, I can change the contents of that function without writing a new constructors. It seems obvious that I should do this, but I'm used to Python. I'm extremely comfortable in that environment and have no problem linking to any part of the standard library from any part of my program because I know I will almost certainly leave that relationship untouched for the life of the project. The situation I'm running into with C feels like I'm trying to hide the language from myself. Will writing a layer of functionality over the C standard library help me in learning the language and developing a codebase, or will it stifle my understanding going forward?

    Read the article

  • Using C++ but not using the language's specific features, should switch to C?

    - by Petruza
    I'm developing a NES emulator as a hobby, in my free time. I use C++ because is the language I use mostly, know mostly and like mostly. But now that I made some advance into the project I realize I'm not using almost any specific features of C++, and could have done it in plain C and getting the same result. I don't use templates, operator overloading, polymorphism, inheritance. So what would you say? should I stay in C++ or rewrite it in C? I won't do this to gain in performance, it could come as a side effect, but the idea is why should I use C++ if I don't need it? The only features of C++ I'm using is classes to encapsulate data and methods, but that can be done as well with structs and functions, I'm using new and delete, but could as well use malloc and free, and I'm using inheritance just for callbacks, which could be achieved with pointers to functions. Remember, it's a hobby project, I have no deadlines, so the overhead time and work that would require a re-write are not a problem, might be fun as well. So, the question is C or C++?

    Read the article

  • Pointers inside a structure [on hold]

    - by user3402552
    I have the next program: #include<stdio.h> #include<stdlib.h> struct a { char *ch; char *str; }; int main() { struct a s1; char ptr[100]; int m, n; printf("\n Enter a string : "); gets(ptr); m = strlen(ptr); s1.ch = (char *)malloc(strlen(ptr) * sizeof(char)); if(s1.ch) { strcpy(s1.ch, ptr); } else { printf("\n Alocation failed!\n"); } printf("\n %s\n\n", s1.ch); while(*s1.ch) { printf(" %c", *(s1.ch)); s1.ch++; } printf("\n\n"); s1.ch = s1.ch - m; printf("\n\n\n %s \n\n", s1.ch); } Is this ok this program in this way ? I mean the pointers should not be initialized ? And if it is not ok, why compile it without errors?

    Read the article

  • How to persuade C fanatics to work on my C++ open source project?

    - by paperjam
    I am launching an open-source project into a space where a lot of the development is still done Linux-kernel-style, i.e. C-language with a low-level mindset. There are multiple benefits to C++ in our space but I fear those used to working in C will be scared off. How can I make the case for the benefits of C++? Specifically, the following C++ attributes are very valuable: concept of objects and reference-counting pointers - really don't want to have to malloc(sizeof(X)) or memcpy() structs templates for specialising whole bodies of code with specific performance optimizations and for avoiding duplication of code. template metaprogramming related to the above syntactic sweetness available (e.g. operator overloading, to be used in very small doses) STL Boost libraries Many of the knee-jerk negative reactions to C++ are illfounded. Performance does not suffer: modern compilers can flatten dozens of call stack levels and avoid bloat through wide use of template specializations. Granted, when using metaprogramming and building multiple specializations of a large call tree, compile time is slower but there are ways to mitigate this. How can I sell C++?

    Read the article

  • using 'ar' tool in Alchemy

    - by paleozogt
    I've found that if you specify a path to Alchemy's 'ar' tool, it won't create the 'l.bc' file necessary to link the library. For example, here is the case when I don't specify a path (it works): asimmons-mac:test asimmons$ echo 'int main() { return 42; }' > testmain.cpp asimmons-mac:test asimmons$ echo 'int test1() { return -1; }' > test1.cpp asimmons-mac:test asimmons$ echo 'int test2() { return 1; }' > test2.cpp asimmons-mac:test asimmons$ g++ -c testmain.cpp asimmons-mac:test asimmons$ g++ -c test1.cpp asimmons-mac:test asimmons$ g++ -c test2.cpp asimmons-mac:test asimmons$ ar cr libtest.a test1.o test2.o asimmons-mac:test asimmons$ g++ testmain.cpp libtest.a llvm-ld, "-o=".(98237.achacks.o = "98237.achacks.exe"), -disable-opt -internalize-public-api-list=_start,malloc,free,__adddi3,__anddi3,__ashldi3,__ashrdi3,__cmpdi2,__divdi3,__fixdfdi,__fixsfdi,__fixunsdfdi,__fixunssfdi,__floatdidf,__floatdisf,__floatunsdidf,__iordi3,__lshldi3,__lshrdi3,__moddi3,__muldi3,__negdi2,__one_cmpldi2,__qdivrem,__adddi3,__anddi3,__ashldi3,__ashrdi3,__cmpdi2,__divdi3,__qdivrem,__fixdfdi,__fixsfdi,__fixunsdfdi,__fixunssfdi,__floatdidf,__floatdisf,__floatunsdidf,__iordi3,__lshldi3,__lshrdi3,__moddi3,__muldi3,__negdi2,__one_cmpldi2,__subdi3,__ucmpdi2,__udivdi3,__umoddi3,__xordi3,__subdi3,__ucmpdi2,__udivdi3,__umoddi3,__xordi3,__error /Users/asimmons/Development/alchemy-darwin-v0.5a/avm2-libc/lib/avm2-libc.l.bc /Users/asimmons/Development/alchemy-darwin-v0.5a/avm2-libc/lib/avm2-libstdc++.l.bc, test.l.bc 98237.achacks.o 98237.achacks.swf, 5593510 bytes written asimmons-mac:test asimmons$ ls -l total 10992 -rwxr-xr-x 1 asimmons staff 5593575 Apr 9 17:44 a.exe -rw------- 1 asimmons staff 1284 Apr 9 17:43 libtest.a -rw-r--r-- 1 asimmons staff 672 Apr 9 17:43 test.l.bc -rw-r--r-- 1 asimmons staff 27 Apr 9 17:43 test1.cpp -rwxr-xr-x 1 asimmons staff 536 Apr 9 17:43 test1.o -rw-r--r-- 1 asimmons staff 26 Apr 9 17:43 test2.cpp -rwxr-xr-x 1 asimmons staff 536 Apr 9 17:43 test2.o -rw-r--r-- 1 asimmons staff 26 Apr 9 17:43 testmain.cpp -rwxr-xr-x 1 asimmons staff 552 Apr 9 17:43 testmain.o asimmons-mac:test asimmons$ And here is an example where I do specify a path (it doesn't work). I try to tell 'ar' to put the library under 'lib' and then link to lib/libtest.a: asimmons-mac:test asimmons$ mkdir lib asimmons-mac:test asimmons$ echo 'int main() { return 42; }' > testmain.cpp asimmons-mac:test asimmons$ echo 'int test1() { return -1; }' > test1.cpp asimmons-mac:test asimmons$ echo 'int test2() { return 1; }' > test2.cpp asimmons-mac:test asimmons$ g++ -c testmain.cpp asimmons-mac:test asimmons$ g++ -c test1.cpp asimmons-mac:test asimmons$ g++ -c test2.cpp asimmons-mac:test asimmons$ ar cr lib/libtest.a test1.o test2.o asimmons-mac:test asimmons$ g++ testmain.cpp lib/libtest.a llvm-ld, "-o=".(98638.achacks.o = "98638.achacks.exe"), -disable-opt -internalize-public-api-list=_start,malloc,free,__adddi3,__anddi3,__ashldi3,__ashrdi3,__cmpdi2,__divdi3,__fixdfdi,__fixsfdi,__fixunsdfdi,__fixunssfdi,__floatdidf,__floatdisf,__floatunsdidf,__iordi3,__lshldi3,__lshrdi3,__moddi3,__muldi3,__negdi2,__one_cmpldi2,__qdivrem,__adddi3,__anddi3,__ashldi3,__ashrdi3,__cmpdi2,__divdi3,__qdivrem,__fixdfdi,__fixsfdi,__fixunsdfdi,__fixunssfdi,__floatdidf,__floatdisf,__floatunsdidf,__iordi3,__lshldi3,__lshrdi3,__moddi3,__muldi3,__negdi2,__one_cmpldi2,__subdi3,__ucmpdi2,__udivdi3,__umoddi3,__xordi3,__subdi3,__ucmpdi2,__udivdi3,__umoddi3,__xordi3,__error /Users/asimmons/Development/alchemy-darwin-v0.5a/avm2-libc/lib/avm2-libc.l.bc /Users/asimmons/Development/alchemy-darwin-v0.5a/avm2-libc/lib/avm2-libstdc++.l.bc, lib/test.l.bc 98638.achacks.o llvm-ld: error: Cannot find linker input 'lib/test.l.bc' asimmons-mac:test asimmons$ ls -l total 56 -rw-r--r-- 1 asimmons staff 552 Apr 9 17:46 98638.achacks.o drwxr-xr-x 3 asimmons staff 102 Apr 9 17:46 lib -rw-r--r-- 1 asimmons staff 27 Apr 9 17:45 test1.cpp -rwxr-xr-x 1 asimmons staff 536 Apr 9 17:46 test1.o -rw-r--r-- 1 asimmons staff 26 Apr 9 17:45 test2.cpp -rwxr-xr-x 1 asimmons staff 536 Apr 9 17:46 test2.o -rw-r--r-- 1 asimmons staff 26 Apr 9 17:45 testmain.cpp -rwxr-xr-x 1 asimmons staff 552 Apr 9 17:45 testmain.o asimmons-mac:test asimmons$ ls -l lib/ total 8 -rw------- 1 asimmons staff 1284 Apr 9 17:46 libtest.a asimmons-mac:test asimmons$ but the linker errors out because it can't find lib/test.l.bc. Notice how in the first example, 'test.l.bc' was generated alongside libtest.a. But in the second example test.l.bc was not generated. Where did it go? This is a contrived example, but in the project I'm trying to build with alchemy the make scripts generate libraries in full paths and then refer to them that way. It seems that alchemy's 'ar' tool is broken if you try to generate a library anywhere other than '.'. Has anyone else seen this? Is there a workaround? fyi, I've also posted this question on the Alchemy formus.

    Read the article

  • iPhone development: pointer being freed was not allocated

    - by w4nderlust
    Hello, i got this message from the debugger: Pixture(1257,0xa0610500) malloc: *** error for object 0x21a8000: pointer being freed was not allocated *** set a breakpoint in malloc_error_break to debug so i did a bit of tracing and got: (gdb) shell malloc_history 1257 0x21a8000 ALLOC 0x2196a00-0x21a89ff [size=73728]: thread_a0610500 |start | main | UIApplicationMain | GSEventRun | GSEventRunModal | CFRunLoopRunInMode | CFRunLoopRunSpecific | __CFRunLoopDoObservers | CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) | CA::Transaction::commit() | CA::Context::commit_transaction(CA::Transaction*) | CALayerDisplayIfNeeded | -[CALayer _display] | CABackingStoreUpdate | backing_callback(CGContext*, void*) | -[CALayer drawInContext:] | -[UIView(CALayerDelegate) drawLayer:inContext:] | -[AvatarView drawRect:] | -[AvatarView overlayPNG:] | +[UIImageUtility createMaskOf:] | UIGraphicsGetImageFromCurrentImageContext | CGBitmapContextCreateImage | create_bitmap_data_provider | malloc | malloc_zone_malloc and i really can't understand what i am doing wrong. here's the code of the [UIImageUtility createMaskOf:] function: + (UIImage *)createMaskOf:(UIImage *)source { CGRect rect = CGRectMake(0, 0, source.size.width, source.size.height); UIGraphicsBeginImageContext(CGSizeMake(source.size.width, source.size.height)); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextTranslateCTM(context, 0, source.size.height); CGContextScaleCTM(context, 1.0, -1.0); UIImage *original = [self createGrayCopy:source]; CGContextRef context2 = CGBitmapContextCreate(NULL, source.size.width, source.size.height, 8, 4 * source.size.width, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipLast); CGContextDrawImage(context2, CGRectMake(0, 0, source.size.width, source.size.height), original.CGImage); CGImageRef unmasked = CGBitmapContextCreateImage(context2); const float myMaskingColorsFrameColor[6] = { 1,256,1,256,1,256 }; CGImageRef mask = CGImageCreateWithMaskingColors(unmasked, myMaskingColorsFrameColor); CGContextSetRGBFillColor (context, 256,256,256, 1); CGContextFillRect(context, rect); CGContextDrawImage(context, rect, mask); UIImage *whiteMasked = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return whiteMasked; } the other custom function called before that is the following: - (UIImage *)overlayPNG:(SinglePart *)sp { NSLog([sp description]); // Rect and context setup CGRect rect = CGRectMake(0, 0, sp.image.size.width, sp.image.size.height); NSLog(@"%f x %f", sp.image.size.width, sp.image.size.height); // Create an image of a color filled rectangle UIImage *baseColor = nil; if (sp.hasOwnColor) { baseColor = [UIImageUtility imageWithRect:rect ofColor:sp.color]; } else { SinglePart *facePart = [editingAvatar.face.partList objectAtIndex:0]; baseColor = [UIImageUtility imageWithRect:rect ofColor:facePart.color]; } // Crete the mask of the layer UIImage *mask = [UIImageUtility createMaskOf:sp.image]; mask = [UIImageUtility createGrayCopy:mask]; // Create a new context for merging the overlay and a mask of the layer UIGraphicsBeginImageContext(CGSizeMake(sp.image.size.width, sp.image.size.height)); CGContextRef context2 = UIGraphicsGetCurrentContext(); // Adjust the coordinate system so that the origin // is in the lower left corner of the view and the // y axis points up CGContextTranslateCTM(context2, 0, sp.image.size.height); CGContextScaleCTM(context2, 1.0, -1.0); // Create masked overlay color layer CGImageRef MaskedImage = CGImageCreateWithMask (baseColor.CGImage, mask.CGImage); // Draw the base color layer CGContextDrawImage(context2, rect, MaskedImage); // Get the result of the masking UIImage* overlayMasked = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); UIGraphicsBeginImageContext(CGSizeMake(sp.image.size.width, sp.image.size.height)); CGContextRef context = UIGraphicsGetCurrentContext(); // Adjust the coordinate system so that the origin // is in the lower left corner of the view and the // y axis points up CGContextTranslateCTM(context, 0, sp.image.size.height); CGContextScaleCTM(context, 1.0, -1.0); // Get the result of the blending of the masked overlay and the base image CGContextDrawImage(context, rect, overlayMasked.CGImage); // Set the blend mode for the next drawn image CGContextSetBlendMode(context, kCGBlendModeOverlay); // Component image drawn CGContextDrawImage(context, rect, sp.image.CGImage); UIImage* blendedImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); CGImageRelease(MaskedImage); return blendedImage; }

    Read the article

  • Concat wchar_t Unicode strings in C?

    - by Doori Bar
    I'm a beginner, I play with FindFirstFileW() of the winapi - C. The unicoded path is: " \\?\c:\Français\", and I would like to concat "*" to this path of type wchar_t (then I will use it as an arg for FindFirstFileW()). I made two test cases of mine, the first is ansi_string() which seem to work fine, the second is unicode_string() - which I don't quite understand how should I concat the additional "*" char to the unicoded path. I write the strings to a file, because I'm not able to print Unicoded characters to stdout. Note: my goal is to learn, which means I'll appreciate guidance and references to the appropriate resources regards my scenario, I'm very much a beginner and this is my first attempt with Unicode. Thanks, Doori Bar #include <stdio.h> #include <stdlib.h> #include <wchar.h> #include <string.h> #include <errno.h> void *error_malloc(int size); void ansi_string(char **str1, char **str2); void unicode_string(wchar_t **wstr1, wchar_t **wstr2); void unicode_string(wchar_t **wstr1, wchar_t **wstr2) { /* assign wstr1 with the path: \\?\c:\Français\ */ *wstr1 = error_malloc((wcslen(L"\\\\?\\c:\\Français\\")+1) *sizeof(**wstr1)); wcscpy(*wstr1,L"\\\\?\\c:\\Français\\"); /* concat wstr1+"*" , assign wstr2 with: \\?\c:\Français\* */ *wstr2 = error_malloc((wcslen(*wstr1) + 1 + 1) * sizeof(**wstr1)); /* swprintf(*wstr2,"%ls*",*wstr1); */ /* how should I concat wstr1+"*"? */ wcscpy(*wstr2,L"\\\\?\\c:\\Français\\"); } void ansi_string(char **str1, char **str2) { /* assign str1 with the path: c:\English\ */ *str1 = error_malloc(strlen("c:\\English\\") + 1); strcpy(*str1,"c:\\English\\"); /* concat str1+"*" , assign str2 with: c:\English\* */ *str2 = error_malloc(strlen(*str1) + 1 + 1); sprintf(*str2,"%s*",*str1); } void *error_malloc(int size) { void *ptr; int errornumber; if ((ptr = malloc(size)) == NULL) { errornumber = errno; fprintf(stderr,"Error: malloc(): %d; Error Message: %s;\n", errornumber,strerror(errornumber)); exit(1); } return ptr; } int main(void) { FILE *outfile; char *str1; char *str2; wchar_t *wstr1; wchar_t *wstr2; if ((outfile = fopen("out.bin","w")) == NULL) { printf("Error: fopen failed."); return 1; } ansi_string(&str1,&str2); fwrite(str2, sizeof(*str2), strlen(str2), outfile); printf("strlen: %d\n",strlen(str2)); printf("sizeof: %d\n",sizeof(*str2)); free(str1); free(str2); unicode_string(&wstr1,&wstr2); fwrite(wstr2, sizeof(*wstr2), wcslen(wstr2), outfile); printf("wcslen: %d\n",wcslen(wstr2)); printf("sizeof: %d\n",sizeof(*wstr2)); free(wstr1); free(wstr2); fclose(outfile); return 0; }

    Read the article

  • Cocoa Basic HTTP Authentication : Advice Needed..

    - by Kristiaan
    Hello all, im looking to read the contents of a webpage that is secured with a user name and password. this is a mac OS X application NOT an iphone app so most of the things i have read on here or been suggested to read do not seem to work. Also i am a total beginner with Xcode and Obj C i was told to have a look at a website that provided sample code to http auth however so far i have had little luck in getting this working. below is the main code for the button press in my application, there is also another unit called Base64 below that has some code in i had to change to even get it compiling (no idea if what i changed is correct mind you). NSURL *url = [NSURL URLWithString:@"my URL"]; NSString *userName = @"UN"; NSString *password = @"PW"; NSError *myError = nil; // create a plaintext string in the format username:password NSMutableString *loginString = (NSMutableString*)[@"" stringByAppendingFormat:@"%@:%@", userName, password]; // employ the Base64 encoding above to encode the authentication tokens char *encodedLoginData = [base64 encode:[loginString dataUsingEncoding:NSUTF8StringEncoding]]; // create the contents of the header NSString *authHeader = [@"Basic " stringByAppendingFormat:@"%@", [NSString stringWithCString:encodedLoginData length:strlen(encodedLoginData)]]; //NSString *authHeader = [@"Basic " stringByAppendingFormat:@"%@", loginString];//[NSString stringWithString:loginString length:strlen(loginString)]]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url cachePolicy: NSURLRequestReloadIgnoringCacheData timeoutInterval: 3]; // add the header to the request. Here's the $$$!!! [request addValue:authHeader forHTTPHeaderField:@"Authorization"]; // perform the reqeust NSURLResponse *response; NSData *data = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &myError]; //*error = myError; // POW, here's the content of the webserver's response. NSString *result = [NSString stringWithCString:[data bytes] length:[data length]]; [myTextView setString:result]; code from the BASE64 file #import "base64.h" static char *alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-"; @implementation Base64 +(char *)encode:(NSData *)plainText { // create an adequately sized buffer for the output. every 3 bytes // become four basically with padding to the next largest integer // divisible by four. char * encodedText = malloc((((([plainText length] % 3) + [plainText length]) / 3) * 4) + 1); char* inputBuffer = malloc([plainText length]); inputBuffer = (char *)[plainText bytes]; int i; int j = 0; // encode, this expands every 3 bytes to 4 for(i = 0; i < [plainText length]; i += 3) { encodedText[j++] = alphabet[(inputBuffer[i] & 0xFC) >> 2]; encodedText[j++] = alphabet[((inputBuffer[i] & 0x03) << 4) | ((inputBuffer[i + 1] & 0xF0) >> 4)]; if(i + 1 >= [plainText length]) // padding encodedText[j++] = '='; else encodedText[j++] = alphabet[((inputBuffer[i + 1] & 0x0F) << 2) | ((inputBuffer[i + 2] & 0xC0) >> 6)]; if(i + 2 >= [plainText length]) // padding encodedText[j++] = '='; else encodedText[j++] = alphabet[inputBuffer[i + 2] & 0x3F]; } // terminate the string encodedText[j] = 0; return encodedText;//outputBuffer; } @end when executing the code it stops on the following line with a EXC_BAD_ACCESS ?!?!? NSString *authHeader = [@"Basic " stringByAppendingFormat:@"%@", [NSString stringWithCString:encodedLoginData length:strlen(encodedLoginData)]]; any help would be appreciated as i am a little clueless on this problem, not being very literate with Cocoa, objective c, xcode is only adding fuel to this fire for me.

    Read the article

  • Encode audio to aac with libavcodec

    - by ryan
    I'm using libavcodec (latest git as of 3/3/10) to encode raw pcm to aac (libfaac support enabled). I do this by calling avcodec_encode_audio repeatedly with codec_context-frame_size samples each time. The first four calls return successfully, but the fifth call never returns. When I use gdb to break, the stack is corrupt. If I use audacity to export the pcm data to a .wav file, then I can use command-line ffmpeg to convert to aac without any issues, so I'm sure it's something I'm doing wrong. I've written a small test program that duplicates my problem. It reads the test data from a file, which is available here: http://birdie.protoven.com/audio.pcm (~2 seconds of signed 16 bit LE pcm) I can make it all work if I use FAAC directly, but the code would be a little cleaner if I could just use libavcodec, as I'm also encoding video, and writing both to an mp4. ffmpeg version info: FFmpeg version git-c280040, Copyright (c) 2000-2010 the FFmpeg developers built on Mar 3 2010 15:40:46 with gcc 4.4.1 configuration: --enable-libfaac --enable-gpl --enable-nonfree --enable-version3 --enable-postproc --enable-pthreads --enable-debug=3 --enable-shared libavutil 50.10. 0 / 50.10. 0 libavcodec 52.55. 0 / 52.55. 0 libavformat 52.54. 0 / 52.54. 0 libavdevice 52. 2. 0 / 52. 2. 0 libswscale 0.10. 0 / 0.10. 0 libpostproc 51. 2. 0 / 51. 2. 0 Is there something I'm not setting, or setting incorrectly in my codec context, maybe? Any help is greatly appreciated! Here is my test code: #include <stdio.h> #include <libavcodec/avcodec.h> void EncodeTest(int sampleRate, int channels, int audioBitrate, uint8_t *audioData, size_t audioSize) { AVCodecContext *audioCodec; AVCodec *codec; uint8_t *buf; int bufSize, frameBytes; avcodec_register_all(); //Set up audio encoder codec = avcodec_find_encoder(CODEC_ID_AAC); if (codec == NULL) return; audioCodec = avcodec_alloc_context(); audioCodec->bit_rate = audioBitrate; audioCodec->sample_fmt = SAMPLE_FMT_S16; audioCodec->sample_rate = sampleRate; audioCodec->channels = channels; audioCodec->profile = FF_PROFILE_AAC_MAIN; audioCodec->time_base = (AVRational){1, sampleRate}; audioCodec->codec_type = CODEC_TYPE_AUDIO; if (avcodec_open(audioCodec, codec) < 0) return; bufSize = FF_MIN_BUFFER_SIZE * 10; buf = (uint8_t *)malloc(bufSize); if (buf == NULL) return; frameBytes = audioCodec->frame_size * audioCodec->channels * 2; while (audioSize >= frameBytes) { int packetSize; packetSize = avcodec_encode_audio(audioCodec, buf, bufSize, (short *)audioData); printf("encoder returned %d bytes of data\n", packetSize); audioData += frameBytes; audioSize -= frameBytes; } } int main() { FILE *stream = fopen("audio.pcm", "rb"); size_t size; uint8_t *buf; if (stream == NULL) { printf("Unable to open file\n"); return 1; } fseek(stream, 0, SEEK_END); size = ftell(stream); fseek(stream, 0, SEEK_SET); buf = (uint8_t *)malloc(size); fread(buf, sizeof(uint8_t), size, stream); fclose(stream); EncodeTest(32000, 2, 448000, buf, size); }

    Read the article

  • Using undefined type.

    - by Knowing me knowing you
    //file list.h #include "stdafx.h" namespace st { struct My_List; typedef My_List list; list* create(const char* name); } //file list.cpp #include "stdafx.h" #include "list.h" namespace st { struct My_List { const char* name_; My_List* left_; My_List* right_; My_List(const char* name):name_(name), left_(nullptr), right_(nullptr) {} My_List(const My_List&); ~My_List() { } void insert(My_List*); void set_name(char* name) { name_ = name; } const char* get_name()const { return name_; } }; typedef My_List list; /*helper class for optor+ */ struct MyChar { const char* my_data_; MyChar(const char* c_string):my_data_(c_string){} operator const char*() { return my_data_; } operator char*() { return const_cast<char*>(my_data_); } }; char* operator+(MyChar left_, MyChar right_) { if (!left_.my_data_ || !right_.my_data_) { return 0; } size_t size = 1;//size is set to one for final '\0' char in an array char* p = "";//if both c_strings are empty this is returned bool has_left_ = false; bool has_right_ = false; if (strlen(left_)) { size += strlen(left_); has_left_ = true; } if (strlen(right_)) { size += strlen(right_); has_right_ = true; } bool both = has_left_ && has_right_ ? true : false; if (both) { p = new char[size](); const void* p_v = p;//just to keep address of beginning of p const char* tmp = left_; /*copying first c_string*/ while (*p++ = *tmp++); tmp = right_; /*one too far after last loop*/ --p; while (*p++ = *tmp++); *p = '\0'; /*go back to the beginning of an array*/ p = static_cast<char*>(const_cast<void*>(p_v)); return p; } else if (has_left_) { return left_; } else if (has_right_) { return right_; } return p;//returns "" if both c_strings were empty } My_List::My_List(const My_List& pat):left_(nullptr),right_(nullptr) { name_ = pat.name_ + MyChar("_cpy"); My_List* pattern = const_cast<My_List*>(&pat); My_List* target = this; while (pattern->right_) { target->right_ = static_cast<My_List*>(malloc(sizeof(My_List))); *target->right_ = *pattern->right_; target->right_->set_name(pattern->right_->get_name() + MyChar("_cpy")); target->right_->left_ = static_cast<My_List*>(malloc(sizeof(My_List))); *target->right_->left_ = *pattern->right_->left_; target->right_->left_->set_name(pattern->right_->left_->get_name() + MyChar("_cpy")); pattern = pattern->right_; target = target->right_; } } void My_List::insert(My_List* obj) { /*to catch first branch*/ My_List* tmp = this; if (tmp->right_) { /*go to the end of right side*/ while (tmp->right_) { tmp = tmp->right_; } tmp->right_ = obj; obj->left_ = tmp; } else { tmp->right_ = obj; obj->left_= this; } } My_List* create(const char* name) { return new My_List(name); } } //file main.cpp #include "stdafx.h" #include "list.h" using namespace st; int _tmain(int argc, _TCHAR* argv[]) { list* my = create("a"); list* b = create("b"); my->insert(b);//HERE I'M GETTING ERROR return 0; } err msg: 'Error 1 error C2027: use of undefined type 'st::My_List' 13' Why? Especially that if I comment this line it will get compiled and create() is using this type.

    Read the article

  • Segmentation. strcmp [C]

    - by FILIaS
    Hello, I have a file with format: [name][number][amount] number is taken as a string. and im using it in a strcmp. Problem is that i get a segmentation fault. I know that on most cases when strcmp signs segmentation fault it means that one of the parameters is null or cant find its "end" ('\0'). I checked with gdb and i cant say if this is the problem.Take a look: > (gdb) bt full > #0 0x08048729 in lookup (hashtable=0x804b008, hashval=27, > number=0x804b740 "6900101001") > list = 0xffffffff > #1 0x080487ac in add (hashtable=0x804b008, > number=0x804b740 "9900101001", name=0x804b730 "Smithpolow", > time=6943) > new_elem = 0xffffffff > hashval = 27 > #2 0x08048b25 in main (argc=1, argv=0xbffff4b4) > number = 0x804b740 "9900101001" > name = 0x804b730 "Smithpolow" > time = 6943 > i = 2 Code: clientsList *lookup_on_Clients(clientsHashTable *hashtable,int hashval,char number[10]) { printf("NUMBER:%s\n",number); clientsList *list=hashtable[hashval].head; for(list; list!=NULL; list=list->next){ if (strcmp(number,list->number)==0) //SEGMENTATION! return list; } return NULL; } int add ( HashTable* hashtable,char number[10],char* name,int time) { List *new_elem; int hashval=hash (hashtable,number); new_elem=hashtable[hashval].head; if(hashtable[hashval].length>0) { if ((lookup (hashtable,hashval,number))!=NULL) {return 0;} } //an den uparxei stoixeio sth lista if (!(new_elem=malloc(sizeof(struct clientsList)))){ return -1;} //insert values for the new elem new_elem->number=strdup(number); new_elem->name=strdup(name); new_elem->time=time; hashtable[hashval].head=new_elem; new_elem->next=NULL; hashtable[hashval].length++; /* rehash existing entries if necessary */ if(hashTableSize(hashtable)>= 2*primes[PrimesIndex]) { hashtable = expand(hashtable); if (hashtable ==NULL){ return 0; } PrimesIndex++; } return 1; } and the main: FILE * File2; if ( ( File2=fopen(" File.txt","r")) !=NULL ) { // File.txt format: [name number time] e.g lountemis 6900254565 700651 int li = 0; char *lin = (char *) malloc(MAX_LINE * sizeof(char)); while(fgets(lin, MAX_LINE, clientFile2) != NULL) { token = my_linetok(lin, " "); if(token != NULL) { char* number ; char* name; int time; int i; for(i = 0; token[i] != NULL; i++) { name=strdup(token[0]); number=strdup(token[1]); time=atoi(token[2]); if (i==2) { int insertDone=0; insertDone =add(my_hash_table,number,name,time); } } free(name); free(number); free(token); } else { printf("Error reading line %s\n", lin); exit(1); } } } else { printf("Error opening file \nEXIT!"); exit(0); }

    Read the article

  • Linked list in C

    - by ScReYm0
    I am still new at lists in C and i got a big problem... First i wanna show you my code for inserting item to the list: void input_books_info(int number_of_books, BOOK *current) { int i; for(i = 0; i < number_of_books; i++) { while(current->next != NULL) current = current->next; current->next = (BOOK *)malloc(sizeof(BOOK)); printf_s("%d book catalog number: ", i + 1); scanf_s("%s", &current->next->catalog_number , 20); printf_s("%d book title: ", i + 1); scanf_s("%s", current->next->title ,80); printf_s("%d book author: ", i + 1); scanf_s("%s", current->next->author ,40); printf_s("%d book publisher: ", i+1); scanf_s("%s", current->next->publisher,80); printf_s("%d book price: ", i + 1); scanf_s("%f", &current->next->price, 5); printf_s("%d book year published: ", i + 1); scanf_s("%d", &current->next->year_published, 5); current->next->next = NULL; printf_s("\n\n"); } } And this is my main function: void main (void) { int number_of_books, t = 1; char book_catalog_number[STRMAX]; char book_title[STRMAX]; char book_author[STRMAX]; char reading_file[STRMAX]; char saving_file[STRMAX]; first = malloc(sizeof(BOOK)); first->next = NULL; /* printf_s("Enter file name: "); gets(saving_file); first->next = book_open(first, saving_file); */ while(t) { char m; printf_s("1. Input \n0. Exit \n\n"); printf_s("Choose operation: "); m = getch(); switch(m) { case '1': printf_s("\ninput number of books: "); scanf_s("%d", &number_of_books); input_books_info(number_of_books, first); printf_s("\n"); break; default: printf_s("\nNo entry found!\n\n\n\n\n"); break; } } } and last maybe here is the problem the printing function: void print_books_info(BOOK *current) { while(current->next != NULL && current != NULL) { printf_s("%s, ", current->next->catalog_number); printf_s("%s, ", current->author); printf_s("%s, ", current->next->title); printf_s("%s, ", current->next->author); printf_s("%s, ", current->next->publisher); printf_s("%.2f, ", current->next->price); printf_s("%d", current->next->year_published); printf_s("\n\n"); current = current->next; } } And my problem is that, when i run the app, program is moving good. But when I start the app, the program is storing only first input of data second and third are lost ... Can you help me to figure out it... ???

    Read the article

  • where is the error in this C code , and how to get rid of the warnings?

    - by mekasperasky
    #include<stdio.h> #include<string.h> //This program is a sorting application that reads a sequence of numbers from a file and prints them on the screen . The reading from the file here , is a call back function . typedef int (*CompFunc)(const char* , const char* ); typedef int (*ReadCheck)(char nullcheck); char array[100]; //Let this fucntion be done in the library itself . It doesnt care as to where the compare function and how is it implemented . Meaning suppose the function wants to do sort in ascending order or in descending order then the changes have to be done by the client code in the "COMPARE" function who will be implementing the lib code . void ReadFile(FILE *fp,ReadCheck rc) { char a; char d[100]; int count = 0,count1=0; a=fgetc(fp); while(1 != (*rc)(a)) { if(a=='\0') { strcpy(array[count],d); count=count+1; } else { d[count1]=a; count1=count1+1; } } } void Bubblesort(int* array , int size , int elem_size , CompFunc cf) { int i,j; int *temp; for( i=0;i < size ;i++) { for ( j=0;j < size -1 ; j++) { // make the callback to the comparision function if(1 == (*cf)(array+j*elem_size,array+ (j+1)*elem_size)) { //interchanging of elements temp = malloc(sizeof(int *) * elem_size); memcpy(temp , array+j*elem_size,elem_size); memcpy(array+j*elem_size,array+(j+1)*elem_size,elem_size); memcpy(array + (j+1)*elem_size , temp , elem_size); free(temp); } } } } //Let these functions be done at the client side int Compare(const char* el1 , const char* el2) { int element1 = *(int*)el1; int element2 = *(int*)el2; if(element1 < element2 ) return -1; if(element1 > element2) return 1 ; return 0; } int ReadChecked(char nullcheck) { if (nullcheck=='\n') return 1; else return 0; } int main() { FILE fp1; int k; fp1=fopen("readdata.txt","r"); Readfile(fp1,&ReadChecked); Bubblesort((char*)array,5,sizeof(array[0]),&Compare); printf("after sorting \n"); for (k=0;k<5;k++) printf("%d",array[k]); return 0; } The error i get is fsc1.c: In function ‘ReadFile’: fsc1.c:19: warning: passing argument 1 of ‘strcpy’ makes pointer from integer without a cast fsc1.c: In function ‘Bubblesort’: fsc1.c:40: warning: passing argument 1 of ‘cf’ from incompatible pointer type fsc1.c:40: warning: passing argument 2 of ‘cf’ from incompatible pointer type fsc1.c:43: warning: incompatible implicit declaration of built-in function ‘malloc’ fsc1.c:47: warning: incompatible implicit declaration of built-in function ‘free’ fsc1.c: In function ‘main’: fsc1.c:80: error: incompatible types in assignment fsc1.c:82: warning: passing argument 1 of ‘Bubblesort’ from incompatible pointer type

    Read the article

< Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >