Search Results

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

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

  • How do I enumerate all monitors in Windows 7?

    - by Jon Tackabury
    I am trying to enumerate all the monitors in Windows 7, and according to MSDN, using the QueryDisplayConfig method is the correct way to do this. All of this code works fine, and returns a couple of arrays, one with paths and one with modes. However, it doesn't have the same monitor ID's as Windows. I am trying to build an array of all the monitors that appear in the Windows 7 "Screen Resolution" dialog. The paths collection return far too many items, and I'm not sure how to tell if it's a valid non-active monitor. Any help would be much appreciated. UINT32 PathArraySize = 0; UINT32 ModeArraySize = 0; DISPLAYCONFIG_PATH_INFO* PathArray; DISPLAYCONFIG_MODE_INFO* ModeArray; GetDisplayConfigBufferSizes( QDC_ALL_PATHS, &PathArraySize, &ModeArraySize); PathArray = (DISPLAYCONFIG_PATH_INFO*)malloc( PathArraySize * sizeof(DISPLAYCONFIG_PATH_INFO)); memset(PathArray, 0, PathArraySize * sizeof(DISPLAYCONFIG_PATH_INFO)); ModeArray = (DISPLAYCONFIG_MODE_INFO*)malloc( ModeArraySize * sizeof(DISPLAYCONFIG_MODE_INFO)); memset(ModeArray, 0, ModeArraySize * sizeof(DISPLAYCONFIG_MODE_INFO)); LONG rtn = QueryDisplayConfig( QDC_ALL_PATHS, &PathArraySize, PathArray, &ModeArraySize, ModeArray, NULL);

    Read the article

  • PHP PCRE differences on testing and hosting servers

    - by Gary Pearman
    Hi all, I've got the following regular expression that works fine on my testing server, but just returns an empty string on my hosted server. $text = preg_replace('~[^\\pL\d]+~u', $use, $text); Now I'm pretty sure this comes down to the hosting server version of PCRE not being compiled with Unicode property support enabled. The differences in the two versions are as follows: My server: PCRE version 7.8 2008-09-05 Compiled with UTF-8 support Unicode properties support Newline sequence is LF \R matches all Unicode newlines Internal link size = 2 POSIX malloc threshold = 10 Default match limit = 10000000 Default recursion depth limit = 10000000 Match recursion uses stack Hosting server: PCRE version 4.5 01-December-2003 Compiled with UTF-8 support Newline character is LF Internal link size = 2 POSIX malloc threshold = 10 Default match limit = 10000000 Match recursion uses stack Also note that the version on the hosting server (the same version PHP is compiled against) is pretty old. What confuses me though, is that pcretest fails on both servers from the command line with re> ~[^\\pL\d]+~u ** Unknown option 'u' although this regexp works fine when run from PHP on my server. So, I guess my questions are does the regular expression fail on the hosting server because of the lack of Unicode properties? Or is there something else that I'm missing? Thanks all, Gaz.

    Read the article

  • iphone encryption not working

    - by Futur
    I have this encryption/decryption implemented and executes with no error, but i am unable to decrypt the data and im not sure whether the data is encrypted, kindly help. - (NSData *)AES256EncryptWithKey:(NSString *)key { char keyPtr[kCCKeySizeAES256+1]; bzero(keyPtr, sizeof(keyPtr)); [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding]; NSUInteger dataLength = [strData length]; data = [[NSData alloc] init]; data = [strData dataUsingEncoding:NSUTF8StringEncoding]; size_t bufferSize = dataLength + kCCBlockSizeAES128; void *pribuffer = malloc(bufferSize); size_t numBytesEncrypted = 0; CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding, keyPtr, kCCKeySizeAES256, NULL /* initialization vector (optional) */, [data bytes], dataLength, /* input */ [data bytes], bufferSize, /* output */ &numBytesEncrypted); if (cryptStatus == kCCSuccess) { return [NSData dataWithBytesNoCopy:data length:numBytesEncrypted]; }} The decryption is : -(NSData *)AES256DecryptWithKey:(NSString *)key andForData:(NSData *)objDataObject { char keyPtr[kCCKeySizeAES256+1]; bzero(keyPtr, sizeof(keyPtr)); [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding]; NSUInteger dataLength = [objDataObject length]; size_t bufferSize = dataLength + kCCBlockSizeAES128; void *buffer = malloc(bufferSize); size_t numBytesDecrypted = 0; CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding, keyPtr, kCCKeySizeAES256, NULL, [objDataObject bytes], dataLength, [objDataObject bytes], bufferSize, &numBytesDecrypted); if (cryptStatus == kCCSuccess) { return [NSData dataWithBytesNoCopy:objDataObject length:numBytesDecrypted]; } } i call the above methods like this: CryptoClass *obj = [CryptoClass new]; NSData *objData = [obj AES256EncryptWithKey:@"hell"]; NSData *val = [obj AES256DecryptWithKey:@"hell" andForData:objData ]; NSLog(@"decrypted string is : %@ AND LENGTH IS %d",[val description],[val length]); Decryption doesnt seem to happen at all and the encryption - i am not sure about it, kindly help me here.

    Read the article

  • How to mmap the stack for the clone() system call on linux?

    - by Joseph Garvin
    The clone() system call on Linux takes a parameter pointing to the stack for the new created thread to use. The obvious way to do this is to simply malloc some space and pass that, but then you have to be sure you've malloc'd as much stack space as that thread will ever use (hard to predict). I remembered that when using pthreads I didn't have to do this, so I was curious what it did instead. I came across this site which explains, "The best solution, used by the Linux pthreads implementation, is to use mmap to allocate memory, with flags specifying a region of memory which is allocated as it is used. This way, memory is allocated for the stack as it is needed, and a segmentation violation will occur if the system is unable to allocate additional memory." The only context I've ever heard mmap used in is for mapping files into memory, and indeed reading the mmap man page it takes a file descriptor. How can this be used for allocating a stack of dynamic length to give to clone()? Is that site just crazy? ;) In either case, doesn't the kernel need to know how to find a free bunch of memory for a new stack anyway, since that's something it has to do all the time as the user launches new processes? Why does a stack pointer even need to be specified in the first place if the kernel can already figure this out?

    Read the article

  • Iterate through main function in C?

    - by Mohit Deshpande
    Here is my main function: int main(int argc, char **argv) { LoadFile(); Node *temp; char *key; switch (GetUserInput()) { case 1: temp = malloc(sizeof(Node)); printf("\nEnter the key of the new node: "); scanf("%s", temp->key); printf("\nEnter the value of the new node: "); scanf("%s", temp->value); AddNode(temp); free(temp); break; case 2: key = malloc(sizeof(char *)); printf("Enter the key of the node you want to delete: "); scanf("%s", key); DeleteNode(key); free(key); break; case 3: PrintAll(); break; case 4: SaveFile(); break; case 5: return 0; break; default: printf("\nWrong choice!\n"); break; } return 0; } The only problem with it is that after any case statement breaks, the program just exits out. I understand why, but I don't know how to fix it. I want the program to repeat itself each time even after the case statements. Would I just say: main(argc, argv); before every break statement?

    Read the article

  • mprotect - how aligning to multiple of pagesize works?

    - by user299988
    Hi, I am not understanding the 'aligning allocated memory' part from the mprotect usage. I am referring to the code example given on http://linux.die.net/man/2/mprotect char *p; char c; /* Allocate a buffer; it will have the default protection of PROT_READ|PROT_WRITE. */ p = malloc(1024+PAGESIZE-1); if (!p) { perror("Couldn't malloc(1024)"); exit(errno); } /* Align to a multiple of PAGESIZE, assumed to be a power of two */ p = (char *)(((int) p + PAGESIZE-1) & ~(PAGESIZE-1)); c = p[666]; /* Read; ok */ p[666] = 42; /* Write; ok */ /* Mark the buffer read-only. */ if (mprotect(p, 1024, PROT_READ)) { perror("Couldn't mprotect"); exit(errno); } For my understanding, I tried using a PAGESIZE of 16, and 0010 as address of p. I ended up getting 0001 as the result of (((int) p + PAGESIZE-1) & ~(PAGESIZE-1)). Could you please clarify how this whole 'alignment' works? Thanks,

    Read the article

  • Need help in reading callgrind output

    - by n179911
    Hi, I have run callgrind with my application like this "valgrind --tool=callgrind MyApplication" and then call 'callgrind_annotate --auto=yes ./callgrind.out.2489' I see output like 768,097,560 PROGRAM TOTALS -------------------------------------------------------------------------------- Ir file:function -------------------------------------------------------------------------------- 18,624,794 /build/buildd/eglibc-2.11.1/elf/dl-lookup.c:do_lookup_x [/lib/ld-2.11.1.so] 18,149,492 /src/js/src/jsgc.cpp:JS_CallTracer'2 [/src/firefox-debug-objdir/js/src/libmozjs.so] 16,328,897 /src/layout/style/nsCSSDataBlock.cpp:nsCSSExpandedDataBlock::DoAssertInitialState() [/src/firefox-debug-objdir/toolkit/library/libxul.so] 13,376,634 /build/buildd/eglibc-2.11.1/nptl/pthread_getspecific.c:pthread_getspecific [/lib/libpthread-2.11.1.so] 13,005,623 /build/buildd/eglibc-2.11.1/malloc/malloc.c:_int_malloc [/lib/libc-2.11.1.so] 10,404,453 ???:0x0000000000009190 [/usr/lib/libpangocairo-1.0.so.0.2800.0] 10,358,646 /src/xpcom/io/nsFastLoadFile.cpp:NS_AccumulateFastLoadChecksum(unsigned int*, unsigned char const*, unsigned int, int) [/src/firefox-debug-objdir/toolkit/library/libxul.so] 8,543,634 /src/js/src/jsscan.cpp:js_GetToken [/src/firefox-debug-objdir/js/src/libmozjs.so] 7,451,273 /src/xpcom/typelib/xpt/src/xpt_arena.c:XPT_ArenaMalloc [/src/firefox-debug-objdir/toolkit/library/libxul.so] 7,335,131 ???:g_type_check_instance_is_a [/usr/lib/libgobject-2.0.so.0.2400.0] I have a few questions: What does the number on the right mean? Does it mean it spend accumulative that long in calling the function on the right? How can I tell how many times that function has been called and Does that include the time spend in calling the functions called by that function? What does line with ??? mean? e.g. ???:0x0000000000009190 [/usr/lib/libpangocairo-1.0.so.0.2800.0] Thank you.

    Read the article

  • C: Proper syntax for allocating memory using pointers to pointers.

    - by ~kero-05h
    This is my first time posting here, hopefully I will not make a fool of myself. I am trying to use a function to allocate memory to a pointer, copy text to the buffer, and then change a character. I keep getting a segfault and have tried looking up the answer, my syntax is probably wrong, I could use some enlightenment. /* My objective is to pass a buffer to my Copy function, allocate room, and copy text to it. Then I want to modify the text and print it.*/ #include <stdio.h> #include <stdlib.h> #include <string.h> int Copy(char **Buffer, char *Text); int main() { char *Text = malloc(sizeof(char) * 100); char *Buffer; strncpy(Text, "1234567890\n", 100); Copy(&Buffer, Text); } int Copy(char **Buffer, char *Text) { int count; count = strlen(Text)+1; *Buffer = malloc(sizeof(char) * count); strncpy(*Buffer, Text, 5); *Buffer[2] = 'A'; /* This results in a segfault. "*Buffer[1] = 'A';" results in no differece in the output. */ printf("%s\n", *Buffer); }

    Read the article

  • C dynamic memory allocation for table of structs

    - by JosiP
    Hi here is my code. I want to dynamincly change no of elemnts in table with structs __state: typedef struct __state{ long int timestamp; int val; int prev_value; }*state_p, state_t; int main(int argc, char **argv){ int zm; int previous_state = 0; int state = 0; int i = 0; int j; state_p st; //here i want to have 20 structs st. st = (state_p) malloc(sizeof(state_t) * 20); while(1){ previous_state = state; scanf("%d", &state); printf("%d, %d\n", state, previous_state); if (previous_state != state){ printf("state changed %d %d\n", previous_state, state); // here i got compile error: main.c: In function ‘main’: main.c:30: error: incompatible type for argument 1 of ‘save_state’ main.c:34: error: invalid type argument of ‘->’ main.c:34: error: invalid type argument of ‘->’ save_state(st[i],previous_state, state); } i++; } return 0; } I suppose i have to change that st[i] to smth like st+ptr ? where pointer is incermeting in each loop iteration ? Or am I wrong ? When i change code: initialization into state_p st[20] and in each loop iteration i put st[i] = (state_p)malloc(sizeof(state_t)) everything works fine, but i want to dynammicly change number of elemets in that table. Thx in advance for any help

    Read the article

  • template style matrix implementation in c

    - by monkeyking
    From time to time I use the following code for generating a matrix style datastructure typedef double myType; typedef struct matrix_t{ |Compilation started at Mon Apr 5 02:24:15 myType **matrix; | size_t x; |gcc structreaderGeneral.c -std=gnu99 -lz size_t y; | }matrix; |Compilation finished at Mon Apr 5 02:24:15 | | matrix alloc_matrix(size_t x, size_t y){ | if(0) | fprintf(stderr,"\t-> Alloc matrix with dim (%lu,%lu) byteprline=%lu bytetotal:%l\| u\n",x,y,y*sizeof(myType),x*y*sizeof(myType)); | | myType **m = (myType **)malloc(x*sizeof(myType **)); | for(size_t i=0;i<x;i++) | m[i] =(myType *) malloc(y*sizeof(myType *)); | | matrix ret; | ret.x=x; | ret.y=y; | ret.matrix=m; | return ret; | } And then I would change my typedef accordingly if I needed a different kind of type for the entries in my matrix. Now I need 2 matrices with different types, an easy solution would be to copy/paste the code, but is there some way to do a template styled implementation. Thanks

    Read the article

  • iPhone: Leak with UIWebView loading Office documents. Any ideas how to avoid it?

    - by Thomas Tempelmann
    While there are already quite a few posts about leaks around UIWebView, mine is a bit more special, I believe, and thus deserves its own post here. I see a reproducible large leak every time I load a Office document such as a Word or Excel file. For instance, every time I display a 180KB .doc file, I get a 100KB leak. And that happens with both the simulator and an actual device, running OS 3.1.3. The leak is not visible with the Leaks instrument but only by looking at the malloc instances via the ObjectAlloc instrument. Here's a picture from the instruments trace: I've also made a demo project, UIWebView-Leak.zip, so you can verify this yourself. To see the leak, use the ObjectAlloc instrument, switch to the view where you see individual allocation objects, and sort by size so that you see the large ones in a group, just like in my picture above. Then view a Office document a few times and find the Malloc objects that keep staying "Live" even after the actual UIWebView has been freed. Is this a known bug? Or is there any way I can avoid these leaks? I.e, have you successfully shown Office documents on an iPhone withing getting such leaks? Note: I've reported this as a bug to Apple now, too (ID 7950594) I am still waiting for someone (including Apple) to confirm this as a true leak or show why it isn't (i.e. that I do something wrong or make wrong assumptions)

    Read the article

  • Valgrind 'noise', what does it mean?

    - by Chris Huang-Leaver
    When I used valgrind to help debug an app I was working on I notice a huge about of noise which seems to be complaining about standard libraries. As a test I did this; echo 'int main() {return 0;}' | gcc -x c -o test - Then I did this; valgrind ./test ==1096== Use of uninitialised value of size 8 ==1096== at 0x400A202: _dl_new_object (in /lib64/ld-2.10.1.so) ==1096== by 0x400607F: _dl_map_object_from_fd (in /lib64/ld-2.10.1.so) ==1096== by 0x4007A2C: _dl_map_object (in /lib64/ld-2.10.1.so) ==1096== by 0x400199A: map_doit (in /lib64/ld-2.10.1.so) ==1096== by 0x400D495: _dl_catch_error (in /lib64/ld-2.10.1.so) ==1096== by 0x400189E: do_preload (in /lib64/ld-2.10.1.so) ==1096== by 0x4003CCD: dl_main (in /lib64/ld-2.10.1.so) ==1096== by 0x401404B: _dl_sysdep_start (in /lib64/ld-2.10.1.so) ==1096== by 0x4001471: _dl_start (in /lib64/ld-2.10.1.so) ==1096== by 0x4000BA7: (within /lib64/ld-2.10.1.so) * large block of similar snipped * ==1096== Use of uninitialised value of size 8 ==1096== at 0x4F35FDD: (within /lib64/libc-2.10.1.so) ==1096== by 0x4F35B11: (within /lib64/libc-2.10.1.so) ==1096== by 0x4A1E61C: _vgnU_freeres (vg_preloaded.c:60) ==1096== by 0x4E5F2E4: __run_exit_handlers (in /lib64/libc-2.10.1.so) ==1096== by 0x4E5F354: exit (in /lib64/libc-2.10.1.so) ==1096== by 0x4E48A2C: (below main) (in /lib64/libc-2.10.1.so) ==1096== ==1096== ERROR SUMMARY: 3819 errors from 298 contexts (suppressed: 876 from 4) ==1096== malloc/free: in use at exit: 0 bytes in 0 blocks. ==1096== malloc/free: 0 allocs, 0 frees, 0 bytes allocated. ==1096== For counts of detected errors, rerun with: -v ==1096== Use --track-origins=yes to see where uninitialised values come from ==1096== All heap blocks were freed -- no leaks are possible. You can see the full result here: http://pastebin.com/gcTN8xGp I have two questions; firstly is there a way to suppress all the noise? --show-below-main is set to no by default, but there doesn't appear to be a --show-after-main equivalent.

    Read the article

  • va_arg with pointers

    - by Yktula
    I want to initialize a linked list with pointer arguments like so: /* * Initialize a linked list using variadic arguments * Returns the number of structures initialized */ int init_structures(struct structure *first, ...) { struct structure *s; unsigned int count = 0; va_list va; va_start(va, first); for (s = first; s != NULL; s = va_arg(va, (struct structure *))) { if ((s = malloc(sizeof(struct structure))) == NULL) { perror("malloc"); exit(EXIT_FAILURE); } count++; } va_end(va); return count; } The problem is that clang errors type name requires a specifier or qualifier at va_arg(va, (struct structure *)), and says that the type specifier defaults to int. It also notes instantiated form at (struct structure *) and struct structure *. This, what seems to be getting assigned to s is int (struct structure *). It compiles fine when parentheses are removed from (struct structure *), but the structures that are supposed to be initialized are inaccessible. Why is int assumed when parentheses are around the type argument passed to va_arg? How can I fix this?

    Read the article

  • Question about memory allocation when initializing char arrays in C/C++.

    - by Carlos Nunez
    Before anything, I apologize if this question has been asked before. I am programming a simple packet sniffer for a class project. For a little while, I ran into the issue where the source and destination of a packet appeared to be the same. For example, the source and destination of an Ethernet frame would be the same MAC address all of the time. I custom-made ether_ntoa(char *) because Windows does not seem to have ethernet.h like Linux does. Code snippet is below: char *ether_ntoa(u_char etheraddr[ETHER_ADDR_LEN]) { int i, j; char eout[32]; for(i = 0, j = 0; i < 5; i++) { eout[j++] = etheraddr[i] >> 4; eout[j++] = etheraddr[i] & 0xF; eout[j++] = ':'; } eout[j++] = etheraddr[i] >> 4; eout[j++] = etheraddr[i] & 0xF; eout[j++] = '\0'; for(i = 0; i < 17; i++) { if(eout[i] < 10) eout[i] += 0x30; else if(eout[i] < 16) eout[i] += 0x57; } return(eout); } I solved the problem by using malloc() to have the compiler assign memory (i.e. instead of char eout[32], I used char * eout; eout = (char *) malloc (32);). However, I thought that the compiler assigned different memory locations when one sized a char-array at compile time. Is this incorrect? Thanks! Carlos Nunez

    Read the article

  • forcing stack w/i 32bit when -m64 -mcmodel=small

    - by chaosless
    have C sources that must compile in 32bit and 64bit for multiple platforms. structure that takes the address of a buffer - need to fit address in a 32bit value. obviously where possible these structures will use natural sized void * or char * pointers. however for some parts an api specifies the size of these pointers as 32bit. on x86_64 linux with -m64 -mcmodel=small tboth static data and malloc()'d data fit within the 2Gb range. data on the stack, however, still starts in high memory. so given a small utility _to_32() such as: int _to_32( long l ) { int i = l & 0xffffffff; assert( i == l ); return i; } then: char *cp = malloc( 100 ); int a = _to_32( cp ); will work reliably, as would: static char buff[ 100 ]; int a = _to_32( buff ); but: char buff[ 100 ]; int a = _to_32( buff ); will fail the assert(). anyone have a solution for this without writing custom linker scripts? or any ideas how to arrange the linker section for stack data, would appear it is being put in this section in the linker script: .lbss : { *(.dynlbss) *(.lbss .lbss.* .gnu.linkonce.lb.*) *(LARGE_COMMON) } thanks!

    Read the article

  • error: invalid type argument of '->' (have 'struct node')

    - by Roshan S.A
    Why cant i access the pointer "Cells" like an array ? i have allocated the appropriate memory why wont it act like an array here? it works like an array for a pointer of basic data types. #include<stdio.h> #include<stdlib.h> #include<ctype.h> #define MAX 10 struct node { int e; struct node *next; }; typedef struct node *List; typedef struct node *Position; struct Hashtable { int Tablesize; List Cells; }; typedef struct Hashtable *HashT; HashT Initialize(int SIZE,HashT H) { int i; H=(HashT)malloc(sizeof(struct Hashtable)); if(H!=NULL) { H->Tablesize=SIZE; printf("\n\t%d",H->Tablesize); H->Cells=(List)malloc(sizeof(struct node)* H->Tablesize); should it not act like an array from here on? if(H->Cells!=NULL) { for(i=0;i<H->Tablesize;i++) the following lines are the ones that throw the error { H->Cells[i]->next=NULL; H->Cells[i]->e=i; printf("\n %d",H->Cells[i]->e); } } } else printf("\nError!Out of Space"); } int main() { HashT H; H=Initialize(10,H); return 0; } The error I get is as in the title-error: invalid type argument of '->' (have 'struct node').

    Read the article

  • Failure remediation strategy for File I/O

    - by Brett
    I'm doing buffered IO into a file, both read and write. I'm using fopen(), fseeko(), standard ANSI C file I/O functions. In all cases, I'm writing to a standard local file on a disk. How often do these file I/O operations fail, and what should the strategy be for failures? I'm not exactly looking for stats, but I'm looking for a general purpose statement on how far I should go to handle error conditions. For instance, I think everyone recognizes that malloc() could and probably will fail someday on some user's machine and the developer should check for a NULL being returned, but there is no great remediation strategy since it probably means the system is out of memory. At least, this seems to be the approach taken with malloc() on desktop systems, embedded systems are different. Likewise, is it worth reattempting a file I/O operation, or should I just consider a failure to be basically unrecoverable, etc. I would appreciate some code samples demonstrating proper usage, or a library guide reference that indicates how this is to be handled. Any other data is, of course, welcome.

    Read the article

  • leak in fgets when assigning to buffer

    - by monkeyking
    I'm having problems understanding why following code leaks in one case, and not in the other case. The difference is while(NULL!=fgets(buffer,length,file))//doesnt leak while(NULL!=(buffer=fgets(buffer,length,file))//leaks I thought it would be the same. Full code below. #include <stdio.h> #include <stdlib.h> #define LENS 10000 void no_leak(const char* argv){ char *buffer = (char *) malloc(LENS); FILE *fp=fopen(argv,"r"); while(NULL!=fgets(buffer,LENS,fp)){ fprintf(stderr,"%s",buffer); } fclose(fp); fprintf(stderr,"%s\n",buffer); free(buffer); } void with_leak(const char* argv){ char *buffer = (char *) malloc(LENS); FILE *fp=fopen(argv,"r"); while(NULL!=(buffer=fgets(buffer,LENS,fp))){ fprintf(stderr,"%s",buffer); } fclose(fp); fprintf(stderr,"%s\n",buffer); free(buffer); }

    Read the article

  • passing argument 1 of 'atoi' makes pointer from integer without a cast....can any body help me..

    - by somasekhar
    #include<stdio.h> #include<string.h> #include<stdlib.h> int main(){ int n; int a,b,ans[10000]; char *c,*d,*e; int i = 0; c = (char*)(malloc(20 * sizeof(char))); d = (char*)(malloc(20 * sizeof(char))); scanf("%d",&n); while(i < n){ scanf("%d",&a); scanf("%d",&b); itoa(a,c,10); itoa(b,d,10); a = atoi(strrev(c)) + atoi(strrev(d)); itoa(a,c,10); e = c; while(*e == '0')e++; ans[i] = atoi(strrev(e)); i++; } i = 0; while(i < n){ printf("%d\n",ans[i]); i++; } }

    Read the article

  • Memory efficient collection class

    - by Joe
    I'm building an array of dictionaries (called keys) in my iphone application to hold the section names and row counts for a tableview. the code looks like this: [self.results removeAllObjects]; [self.keys removeAllObjects]; NSUInteger i,j = 0; NSString *key = [NSString string]; NSString *prevKey = [NSString string]; if ([self.allResults count] > 0) { prevKey = [NSString stringWithString:[[[self.allResults objectAtIndex:0] valueForKey:@"name"] substringToIndex:1]]; for (NSDictionary *theDict in self.allResults) { key = [NSString stringWithString:[[theDict valueForKey:@"name"] substringToIndex:1]]; if (![key isEqualToString:prevKey]) { NSDictionary *newDictionary = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:i],@"count", prevKey,@"section", [NSNumber numberWithInt:j], @"total",nil]; [self.keys addObject:newDictionary]; prevKey = [NSString stringWithString:key]; i = 1; } else { i++; } j++; } NSDictionary *newDictionary = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:i],@"count", prevKey,@"section", [NSNumber numberWithInt:j], @"total",nil]; [self.keys addObject:newDictionary]; } [self.tableview reloadData]; The code works fine first time through but I sometimes have to rebuild the entire table so I redo this code which orks fine on the simulator, but on my device the program bombs when I execute the reloadData line : malloc: *** mmap(size=3772944384) failed (error code=12) *** error: can't allocate region *** set a breakpoint in malloc_error_break to debug malloc: *** mmap(size=3772944384) failed (error code=12) *** error: can't allocate region *** set a breakpoint in malloc_error_break to debug Program received signal: “EXC_BAD_ACCESS”. If I remove the reloadData line the code works on the device. I'm wondering if this is something to do with the way I've built the keys array (ie using autoreleased strings and dictionaries).

    Read the article

  • How to declare a 2D array of 2D array pointers and access them?

    - by vikramtheone
    Hi Guys, How can I declare an 2D array of 2D Pointers? And later access the individual array elements of the 2D arrays. Is my approach correct? void alloc_2D(int ***memory, unsigned int rows, unsigned int cols); int main() { int i, j; int **ptr; int **array[10][10]; for(i=0;i<10;i++) { for(j=0;j<10;j++) { alloc_2D(&ptr, 10, 10); array[i][j] = ptr; } } //After I do this, how can I access the 10 individual 2D arrays? return 0; } void alloc_2D(int ***memory, unsigned int rows, unsigned int cols) { int **ptr; *memory = NULL; ptr = malloc(rows * sizeof(int*)); if(ptr == NULL) { printf("\nERROR: Memory allocation failed!"); } else { int i; for(i = 0; i< rows; i++) { ptr[i] = malloc(cols * sizeof(float)); if(ptr[i]==NULL) { printf("\nERROR: Memory allocation failed!"); } } } *memory = ptr; }

    Read the article

  • How are two-dimensional arrays formatted in memory?

    - by Chris Cooper
    In C, I know I can dynamically allocate a two-dimensional array on the heap using the following code: int** someNumbers = malloc(arrayRows*sizeof(int*)); for (i = 0; i < arrayRows; i++) { someNumbers[i] = malloc(arrayColumns*sizeof(int)); } Clearly, this actually creates a one-dimensional array of pointers to a bunch of separate one-dimensional arrays of integers, and "The System" can figure you what I mean when I ask for: someNumbers[4][2]; But when I statically declare a 2D array, as in the following line...: int someNumbers[ARRAY_ROWS][ARRAY_COLUMNS]; ...does a similar structure get created on the stack, or is it of another form completely? (i.e. is it a 1D array of pointers? If not, what is it, and how do references to it get figured out?) Also, when I said, "The System," what is actually responsible for figuring that out? The kernel? Or does the C compiler sort it out while compiling?

    Read the article

  • Appending unique values only in a linked list in C

    - by LuckySlevin
    typedef struct child {int count; char word[100]; inner_list*next;} child; typedef struct parent { char data [100]; inner_list * head; int count; outer_list * next; } parent; void append(child **q,char num[100],int size) { child *temp,*r,*temp2,*temp3; parent *out=NULL; temp = *q; temp2 = *q; temp3 = *q; char *str; if(*q==NULL) { temp = (child *)malloc(sizeof(child)); strcpy(temp->word,num); temp->count =size; temp->next=NULL; *q=temp; } else { temp = *q; while(temp->next !=NULL) { temp=temp->next; } r = (child *)malloc(sizeof(child)); strcpy(r->word,num); r->count = size; r->next=NULL; temp->next=r; } } This is my append function which I use for adding an element to my child list. But my problem is it only should append unique values which are followed by a string. Which means : Inputs : aaa bbb aaa ccc aaa bbb ccc aaa Append should act : For aaa string there should be a list like bbb->ccc(Not bbb->ccc->bbb since bbb is already there if bbb is coming more than one time it should be increase count only.) For bbb string there should be list like aaa->ccc only For ccc string there should be list like aaa only I hope i could make myself clear. Is there any ideas? Please ask for further info.

    Read the article

  • How to declare array of 2D array pointers and access them?

    - by vikramtheone
    Hi Guys, How can I declare an 2D array of 2D Pointers? And later access the individual array elements of the 2D arrays. Is my approach correct? main() { int i, j; int **array[10][10]; int **ptr = NULL; for(i=0;i<10;i++) { for(j=0j<10;j++) { alloc_2D(&ptr, 10, 10); array[i][j] = ptr; } } //After I do this, how can I access the individual 2D array //and then the individual elements of the 2D arrays? } void alloc_2D(float ***memory, unsigned int rows, unsigned int cols) { float **ptr; *memory = NULL; ptr = malloc(rows * sizeof(float*)); if(ptr == NULL) { status = ERROR; printf("\nERROR: Memory allocation failed!"); } else { int i; for(i = 0; i< rows; i++) { ptr[i] = malloc(cols * sizeof(float)); if(ptr[i]==NULL) { status = ERROR; printf("\nERROR: Memory allocation failed!"); } } } *memory = ptr; }

    Read the article

  • Why cant we create Object if constructor is in private section?

    - by Abhi
    Dear all I want to know why cant we create object if the constructor is in private section. I know that if i make a method static i can call that method using <classname> :: <methodname(...)>; But why cant we create object is my doubt... I also know if my method is not static then also i can call function by the following... class A { A(); public: void fun1(); void fun2(); void fun3(); }; int main() { A *obj =(A*)malloc(sizeof(A)); //Here we can't use new A() because constructor is in private //but we can use malloc with it, but it will not call the constructor //and hence it is harmful because object may not be in usable state. obj->fun1(); obj->fun2(); obj->fun3(); } So only doubt is why cant we create object when constructor is in private section? Thanks in advance

    Read the article

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