Search Results

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

Page 2/31 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • c++ malloc segmentation fault

    - by chnet
    I have a problem about malloc(). It is weird. My code is in the following. I use random generator to generate elements for an array. The array is opened by malloc(). If the array size is smaller than 8192, it is OK. If the size is larger than 8192, it shows segment fault. void random_generator(int num, int * array) { srand((unsigned)time(0)); int random_integer; for(int index=0; index< num; index++){ random_integer = (rand()%10000)+1; *(array+index) = random_integer; cout << index << endl; } } int main() { int array_size = 10000; int *input_array; input_array = (int*) malloc((array_size)); random_generator(8192, input_array); // if the number is larger than 8192, segment fault free(input_array); }

    Read the article

  • C Programming: malloc and free within a loop

    - by kouei
    Hi all, I just started out with C and have very little knowledge about performance issues with malloc() and free(). My question is as such: if I were to call malloc() followed by free() in a while-loop that loops for, say, 20 times, would it run slower compared to if I were to call free() outside the loop? I am actually using the first method to allocate memory to a buffer, read a string of variable length in a file, perform some string operation, and then clear the buffer after every iteration. If my method results in a lot of overhead then I'd like to ask for a better way for me to achieve the same results. Sorry for my bad English. Thanks and regards, K

    Read the article

  • C Programming: malloc() for a 2D array (using pointer-to-pointer)

    - by vikramtheone
    Hi Guys, yesterday I had posted a question: How should I pass a pointer to a function and allocate memory for the passed pointer from inside the called function? From the answers I got, I was able to understand what mistake I was doing. I'm facing a new problem now, can anyone help out with this? I want to dynamically allocate a 2D array, so I'm passing a Pointer-to-Pointer from my main() to another function called alloc_2D_pixels(...), where I use malloc(...) and for(...) loop to allocate memory for the 2D array. Well, after returning from the alloc_2D_pixels(...) function, the pointer-to-pointer still remains NULL, so naturally, when I try accessing or try to free(...) the Pointer-to-Pointer, the program hangs. Can anyone suggest me what mistakes I'm doing here? Help!!! Vikram SOURCE: main() { unsigned char **ptr; unsigned int rows, cols; if(alloc_2D_pixels(&ptr, rows, cols)==ERROR) // Satisfies this condition printf("Memory for the 2D array not allocated"); // NO ERROR is returned if(ptr == NULL) // ptr is NULL so no memory was allocated printf("Yes its NULL!"); // Because ptr is NULL, with any of these 3 statements below the program HANGS ptr[0][0] = 10; printf("Element: %d",ptr[0][0]); free_2D_alloc(&ptr); } signed char alloc_2D_pixels(unsigned char ***memory, unsigned int rows, unsigned int cols) { signed char status = NO_ERROR; memory = malloc(rows * sizeof(unsigned char** )); if(memory == NULL) { status = ERROR; printf("ERROR: Memory allocation failed!"); } else { int i; for(i = 0; i< cols; i++) { memory[i] = malloc(cols * sizeof(unsigned char)); if(memory[i]==NULL) { status = ERROR; printf("ERROR: Memory allocation failed!"); } } } // Inserted the statements below for debug purpose only memory[0][0] = (unsigned char)10; // I'm able to access the array from printf("\nElement %d",memory[0][0]); // here with no problems return status; } void free_2D_pixels(unsigned char ***ptr, unsigned int rows) { int i; for(i = 0; i < rows; i++) { free(ptr[i]); } free(ptr); }

    Read the article

  • Taming the malloc/free beast -- tips & tricks

    - by roufamatic
    I've been using C on some projects for a master's degree but have never built production software with it. (.NET & Javascript are my bread and butter.) Obviously, the need to free() memory that you malloc() is critical in C. This is fine, well and good if you can do both in one routine. But as programs grow, and structs deepen, keeping track of what's been malloc'd where and what's appropriate to free gets harder and harder. I've looked around on the interwebs and only found a few generic recommendations for this. What I suspect is that some of you long-time C coders have come up with your own patterns and practices to simplify this process and keep the evil in front of you. So: how do you recommend structuring your C programs to keep dynamic allocations from becoming memory leaks?

    Read the article

  • malloc hangs in Linux

    - by Rahul
    I am using Linux on a 16 G with 2 quad core CPU. There are 8 processes which are doing some work (CPU intensive/network i/o). Out of which 4 have a memory leak (These are test conditions so no problem in having leaks here). Total space is occupied by all processes is around 15.4 G only 200 MB is free in system. Things are fine for some hours. But after that malloc hangs (for a process which doesn't have a memory leak). Its stuck for for more than 4 minutes (Note CPU is not 100% but io has gone up signficantly). Now there is no problem in the hanged process. (It has not corrupted the memory). What malloc is doing? (is it tryibg to defragment or builidng up swap space).I am using SUSE 10. Any pointers?

    Read the article

  • Iphone memory leak with malloc

    - by Icky
    Hello. I have memory leak, found by instruments and it is supposed to be in this line of code: indices = malloc( sizeof(indices[0]) * totalQuads * 6); This is actually a code snippet from a tutorial, something which i think is leak-free so to say. Now I reckon, the error is somewhere else, but I do not know, where. These are the last trackbacks: 5 ColorRun -[EAGLView initWithCoder:] /Users/thomaskopinski/programming/colorrun_3.26/Classes/EAGLView.m:98 4 ColorRun -[EAGLView initGame] /Users/thomaskopinski/programming/colorrun_3.26/Classes/EAGLView.m:201 3 ColorRun -[SpriteSheet initWithImageNamed:spriteWidth:spriteHeight:spacing:imageScale:] /Users/thomaskopinski/programming/colorrun_3.26/SpriteSheet.m:68 2 ColorRun -[Image initWithImage:scale:] /Users/thomaskopinski/programming/colorrun_3.26/Image.m:122 1 ColorRun -[Image initImpl] /Users/thomaskopinski/programming/colorrun_3.26/Image.m:158 0 libSystem.B.dylib malloc Does anyone know how to approach this?

    Read the article

  • Help with memory leak (malloc)

    - by user146780
    I'v followed a tutorial to use OGL tesselaton. In one of the callbacks there is a malloc and it creates a leak every time I render a new frame. void CALLBACK combineCallback(GLdouble coords[3], GLdouble *vertex_data[4], GLfloat weight[4], GLdouble **dataOut) { GLdouble *vertex; vertex = (GLdouble *) malloc(6 * sizeof(GLdouble)); vertex[0] = coords[0]; vertex[1] = coords[1]; vertex[2] = coords[2]; for (int i = 3; i < 6; i++) { vertex[i] = weight[0] * vertex_data[0][i] + weight[1] * vertex_data[0][i] + weight[2] * vertex_data[0][i] + weight[3] * vertex_data[0][i]; } *dataOut = vertex; } I'v tried to free(vertex) but then the polygons did not render. I also tried allocating on the heap then doing delete(vertex) but then the polygon rendered awkwardly. I'm not sure what to do. Thanks

    Read the article

  • question about Doug Lea's malloc

    - by hatorade
    http://gee.cs.oswego.edu/dl/html/malloc.html in making his array for the segmented bins, he makes bins for 8 - 512 using multiples of 8 (so 63 bins, but only the last 62 are ever used). how does he determine the size for the remaining 63 bins? He mentions they are logarithmically spaced, but is there some sort of equation he used to do that optimally?

    Read the article

  • C newbie malloc question

    - by roufamatic
    Why doesn't this print 5? void writeValue(int* value) { value = malloc(sizeof(int)); *value = 5; } int main(int argc, char * argv) { int* value = NULL; writeValue(value); printf("value = %d\n", *value); // error trying to access 0x00000000 } and how can I modify this so it would work while still using a pointer as an argument to writeValue?

    Read the article

  • seg fault caused by malloc and sscanf in a function

    - by Framester
    Hi, I want to open a text file (see below), read the first int in every line and store it in an array, but I get an segmentation fault. I got rid of all gcc warnings, I read through several tutorials I found on the net and searched stackoverflow for solutions, but I could't make out, what I am doing wrong. It works when I have everything in the main function (see example 1), but not when I transfer it to second function (see example 2 further down). In example 2 I get, when I interpret gdb correctly a seg fault at sscanf (line,"%i",classes[i]);. I'm afraid, it could be something trivial, but I already wasted one day on it. Thanks in advance. [Example 1] Even though that works with everything in main: #include<stdio.h> #include<stdlib.h> #include<string.h> const int LENGTH = 1024; int main() { char *filename="somedatafile.txt"; int *classes; int lines; FILE *pfile = NULL; char line[LENGTH]; pfile=fopen(filename,"r"); int numlines=0; char *p; while(fgets(line,LENGTH,pfile)){ numlines++; } rewind(pfile); classes=(int *)malloc(numlines*sizeof(int)); if(classes == NULL){ printf("\nMemory error."); exit(1); } int i=0; while(fgets(line,LENGTH,pfile)){ printf("\n"); p = strtok (line," "); p = strtok (NULL, ", "); sscanf (line,"%i",&classes[i]); i++; } fclose(pfile); return 1; } [Example 2] This does not with the functionality transfered to a function: #include<stdio.h> #include<stdlib.h> #include<string.h> const int LENGTH = 1024; void read_data(int **classes,int *lines, char *filename){ FILE *pfile = NULL; char line[LENGTH]; pfile=fopen(filename,"r"); int numlines=0; char *p; while(fgets(line,LENGTH,pfile)){ numlines++; } rewind(pfile); * classes=(int *)malloc(numlines*sizeof(int)); if(*classes == NULL){ printf("\nMemory error."); exit(1); } int i=0; while(fgets(line,LENGTH,pfile)){ printf("\n"); p = strtok (line," "); p = strtok (NULL, ", "); sscanf (line,"%i",classes[i]); i++; } fclose(pfile); *lines=numlines; } int main() { char *filename="somedatafile.txt"; int *classes; int lines; read_data(&classes, &lines,filename) ; for(int i=0;i<lines;i++){ printf("\nclasses[i]=%i",classes[i]); } return 1; } [Content of somedatafile.txt] 50 21 77 0 28 0 27 48 22 2 55 0 92 0 0 26 36 92 56 4 53 0 82 0 52 -5 29 30 2 1 37 0 76 0 28 18 40 48 8 1 37 0 79 0 34 -26 43 46 2 1 85 0 88 -4 6 1 3 83 80 5 56 0 81 0 -4 11 25 86 62 4 55 -1 95 -3 54 -4 40 41 2 1 53 8 77 0 28 0 23 48 24 4 37 0 101 -7 28 0 64 73 8 1 ...

    Read the article

  • n & x commands&creating pointer&with using malloc [closed]

    - by gcc
    input 23 3 4 4 42 n 23 0 9 9 n n n 3 9 9 x //according to input,i should create int pointer arrays. pointer arrays // starting from 1 (that is initial arrays is arrays[1].when program sees n ,it // must be jumb to arrays 2 // the first int input 23 is num_arrays which used in malloc(sizeof(int)*num_arrays expected output arrays[1] 3 4 5 42 arrays[2] 23 0 9 9 arrays[5] 3 9 9 another input 12 2 3 4 n n 2 3 4 n 12 3 x expected output arrays[1] 2 3 4 arrays[3] 2 3 4 arrays[4] 12 3 x is stopper n is comman to create new pointer array i am new in this site anyone help me how can i write

    Read the article

  • Exception on malloc for a structure in C

    - by Derek
    Hi all, I have a structure defined like so: typedef struct { int n; int *n_p; void **list_pp; size_t rec_size; int n_buffs; size_t buff_size } fl_hdr_type; and in my code I Have a function for initlialization that has the following fl_hdr_type *fl_hdr; fl_hdr = malloc(sizeof(fl_hdr_type) + (buff_size_n * rec_size_n)); where those buffer size are passed in to the function to allow space for the buffers as well. The size is pretty small typically..100*50 or something like that..plenty of memory on this system to allocate it. Any ideas why this fails?

    Read the article

  • malloc()/free() behavior differs between Debian and Redhat

    - by StasM
    I have a Linux app (written in C) that allocates large amount of memory (~60M) in small chunks through malloc() and then frees it (the app continues to run then). This memory is not returned to the OS but stays allocated to the process. Now, the interesting thing here is that this behavior happens only on RedHat Linux and clones (Fedora, Centos, etc.) while on Debian systems the memory is returned back to the OS after all freeing is done. Any ideas why there could be the difference between the two or which setting may control it, etc.?

    Read the article

  • Malloc inside another function (ANSI C)

    - by Casper
    Hi I'll go straight to it. I'm working on an assignment, where I suddenly ran into trouble. I have to allocate a struct from within another function, obviously using pointers. I've been staring at this problem for hours and tried in a million different ways to solve it. This is some sample code (very simplified): ... some_struct s; printf("Before: %d\n", &s"); allocate(&s); printf("After: %d\n", &s"); ... /* The allocation function */ int allocate(some_struct *arg) { arg = malloc(sizeof(some_struct)); printf("In function: %d\n", &arg"); return 0; } This does give me the same address before and after the allocate-call: Before: -1079752900 In function: -1079752928 After: -1079752900 I know it's probably because it makes a copy in the function, but I don't know how to actually work on the pointer I gave as argument. I tried defining some_struct *s instead of some_struct s, but no luck. I tried with: int allocate(some_struct **arg) which works just fine (the allocate-function needs to be changed as well), BUT according to the assignment I may NOT change the declaration, and it HAS to be *arg.. And it would be most correct if I just have to declare some_struct s.. Not some_struct *s. I hope I make sense and some of you out there can help me :P Thanks in advice

    Read the article

  • linux new/delete, malloc/free large memory blocks

    - by brian_mk
    Hi folks, We have a linux system (kubuntu 7.10) that runs a number of CORBA Server processes. The server software uses glibc libraries for memory allocation. The linux PC has 4G physical memory. Swap is disabled for speed reasons. Upon receiving a request to process data, one of the server processes allocates a large data buffer (using the standard C++ operator 'new'). The buffer size varies depening upon a number of parameters but is typically around 1.2G Bytes. It can be up to about 1.9G Bytes. When the request has completed, the buffer is released using 'delete'. This works fine for several consecutive requests that allocate buffers of the same size or if the request allocates a smaller size than the previous. The memory appears to be free'd ok - otherwise buffer allocation attempts would eventually fail after just a couple of requests. In any case, we can see the buffer memory being allocated and freed for each request using tools such as KSysGuard etc. The problem arises when a request requires a buffer larger than the previous. In this case, operator 'new' throws an exception. It's as if the memory that has been free'd from the first allocation cannot be re-allocated even though there is sufficient free physical memory available. If I kill and restart the server process after the first operation, then the second request for a larger buffer size succeeds. i.e. killing the process appears to fully release the freed memory back to the system. Can anyone offer an explanation as to what might be going on here? Could it be some kind of fragmentation or mapping table size issue? I am thinking of replacing new/delete with malloc/free and use mallopt to tune the way the memory is being released to the system. BTW - I'm not sure if it's relevant to our problem, but the server uses Pthreads that get created and destroyed on each processing request. Cheers, Brian.

    Read the article

  • Pointer and malloc issue

    - by Andy
    I am fairly new to C and am getting stuck with arrays and pointers when they refer to strings. I can ask for input of 2 numbers (ints) and then return the one I want (first number or second number) without any issues. But when I request names and try to return them, the program crashes after I enter the first name and not sure why. In theory I am looking to reserve memory for the first name, and then expand it to include a second name. Can anyone explain why this breaks? Thanks! #include <stdio.h> #include <stdlib.h> void main () { int NumItems = 0; NumItems += 1; char* NameList = malloc(sizeof(char[10])*NumItems); printf("Please enter name #1: \n"); scanf("%9s", NameList[0]); fpurge(stdin); NumItems += 1; NameList = realloc(NameList,sizeof(char[10])*NumItems); printf("Please enter name #2: \n"); scanf("%9s", NameList[1]); fpurge(stdin); printf("The first name is: %s",NameList[0]); printf("The second name is: %s",NameList[1]); return 0; }

    Read the article

  • Adobe After Effects Plugin With Cocoa (Overriding malloc)

    - by mustISignUp
    Messing about a bit, i have a working Adobe After Effects plugin with a bit of Obj-c / Cocoa in it (NSArray and custom objects - not ui stuff). The SDK guide states:- Always use After Effects memory allocation functions. In low-memory conditions (such as during RAM preview), it’s very important that plug-ins not compete with After Effects for OS memory, and deal gracefully with out-of-memory conditions. Failing to use our functions can cause lock-ups, crashes, and tech support calls. Don’t do that. If you’re wrapping existing C++ code, overloading new and delete to use our functions will save substantial reimplementation. On Windows, derive all classes from a common base class which implements new and delete. so my question.. is something compatible with the above statement possible in Obj-c?

    Read the article

  • Seg Fault with malloc'd pointers

    - by anon
    I'm making a thread class to use as a wrapper for pthreads. I have a Queue class to use as a queue, but I'm having trouble with it. It seems to allocate and fill the queue struct fine, but when I try to get the data from it, it Seg. faults. http://pastebin.com/Bquqzxt0 (the printf's are for debugging, both throw seg faults) edit: the queue is stored in a dynamically allocated "struct queueset" array as a pointer to the data and an index for the data

    Read the article

  • Adobe After Efects Plugin With Cocoa (Overriding malloc)

    - by mustISignUp
    Messing about a bit, i have a working Adobe After Effects plugin with a bit of Obj-c / Cocoa in it (NSArray and custom objects - not ui stuff). The SDK guide states:- Always use After Effects memory allocation functions. In low-memory conditions (such as during RAM preview), it’s very important that plug-ins not compete with After Effects for OS memory, and deal gracefully with out-of-memory conditions. Failing to use our functions can cause lock-ups, crashes, and tech support calls. Don’t do that. If you’re wrapping existing C++ code, overloading new and delete to use our functions will save substantial reimplementation. On Windows, derive all classes from a common base class which implements new and delete. so my question.. is something compatible with the above statement possible in Obj-c?

    Read the article

  • What happens to class members when malloc is used instead of new?

    - by Felix
    I'm studying for a final exam and I stumbled upon a curious question that was part of the exam our teacher gave last year to some poor souls. The question goes something like this: Is the following program correct, or not? If it is, write down what the program outputs. If it's not, write down why. The program: #include<iostream.h> class cls { int x; public: cls() { x=23; } int get_x(){ return x; } }; int main() { cls *p1, *p2; p1=new cls; p2=(cls*)malloc(sizeof(cls)); int x=p1->get_x()+p2->get_x(); cout<<x; return 0; } My first instinct was to answer with "the program is not correct, as new should be used instead of malloc". However, after compiling the program and seeing it output 23 I realize that that answer might not be correct. The problem is that I was expecting p2->get_x() to return some arbitrary number (whatever happened to be in that spot of the memory when malloc was called). However, it returned 0. I'm not sure whether this is a coincidence or if class members are initialized with 0 when it is malloc-ed. Is this behavior (p2->x being 0 after malloc) the default? Should I have expected this? What would your answer to my teacher's question be? (besides forgetting to #include <stdlib.h> for malloc :P)

    Read the article

  • How should a multi-threaded C application handle a failed malloc()?

    - by user294463
    A part of an application I'm working on is a simple pthread-based server that communicates over a TCP/IP socket. I am writing it in C because it's going to be running in a memory constrained environment. My question is: what should the program do if one of the threads encounters a malloc() that returns NULL? Possibilities I've come up with so far: No special handling. Let malloc() return NULL and let it be dereferenced so that the whole thing segfaults. Exit immediately on a failed malloc(), by calling abort() or exit(-1). Assume that the environment will clean everything up. Jump out of the main event loop and attempt to pthread_join() all the threads, then shut down. The first option is obviously the easiest, but seems very wrong. The second one also seems wrong since I don't know exactly what will happen. The third option seems tempting except for two issues: first, all of the threads need not be joined back to the main thread under normal circumstances and second, in order to complete the thread execution, most of the remaining threads will have to call malloc() again anyway. What shall I do?

    Read the article

  • Problem with using malloc in link lists (urgent ! help please)

    - by Abhinav
    I've been working on this program for five months now. Its a real time application of a sensor network. I create several link lists during the life of the program and Im using malloc for creating a new node in the link. What happens is that the program suddenly stops or goes crazy and restarts. Im using AVR and the microcontroller is ATMEGA 1281. After a lot of debugging I figured out that that the malloc is causing the problem. I do not free the memory after exiting the function that creates a new link so Im guessing that this is eventually causing the heap memory to overflow or something like that. Now if I use the free() function to deallocate the memory at the end of the function using malloc, the program just gets stuck when the control reaches free(). Is this because the memory becomes too clustered after calling free() ? I also create reference tables for example if 'head' is a new link list and I create another list called current and make it equal to head. table *head; table *current = head; After the end of the function if I use free free(current); current = NULL: Then the program gets stuck here. I dont know what to do. What am I doing wrong? Is there a way to increase the size of the heap memory Please help...

    Read the article

  • Is there a fundamental difference between malloc and HeapAlloc (aside from the portability)?

    - by Lambert
    Hi, I'm having code that, for various reasons, I'm trying to port from the C runtime to one that uses the Windows Heap API. I've encountered a problem: If I redirect the malloc/calloc/realloc/free calls to HeapAlloc/HeapReAlloc/HeapFree (with GetProcessHeap for the handle), the memory seems to be allocated correctly (no bad pointer returned, and no exceptions thrown), but the library I'm porting says "failed to allocate memory" for some reason. I've tried this both with the Microsoft CRT (which uses the Heap API underneath) and with another company's run-time library (which uses the Global Memory API underneath); the malloc for both of those works well with the library, but for some reason, using the Heap API directly doesn't work. I've checked that the allocations aren't too big (= 0x7FFF8 bytes), and they're not. The only problem I can think of is memory alignment; is that the case? Or other than that, is there a fundamental difference between the Heap API and the CRT memory API that I'm not aware of? If so, what is it? And if not, then why does the static Microsoft CRT (included with Visual Studio) take some extra steps in malloc/calloc before calling HeapAlloc? I'm suspecting there's a difference but I can't think of what it might be. Thank you!

    Read the article

  • Interview question ranking FizzBuzz (1), implementing malloc (10)

    - by blrs
    I'd like to have your opinion on the difficulty of the following interview question: Find the subarray with maximum sum in an array of integers in O(n) time. This trivial sounding problem was made famous by Jon Bentley in his Programming Pearls where he uses it to demonstrate algorithm design techniques. On a scale of 1-10, 1 being the FizzBuzz (or HoppityHop) test and 10 being implement the C stdlib function malloc(), how would you rank the above problem? I think the people who can best answer this question are those who have read Programming Pearls and have tried to solve this problem on their own. To motivate those who haven't, 'Programming Pearls' gets featured many times in the 'Top 10 programming books' list.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >