Search Results

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

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

  • How can I malloc an array of struct to do the following using file operation?

    - by RHN
    How can malloc an array of struct to do the following using file operation? the file is .txt input in the file is like: 10 22 3.3 33 4.4 I want to read the first line from the file and then I want to malloc an array of input structures equal to the number of lines to be read in from the file. Then I want to read in the data from the file and into the array of structures malloc. Later on I want to store the size of the array into the input variable size. return an array.After this I want to create another function that print out the data in the input variable in the same form like input file and suppose a function call clean_data will free the malloc memory at the end. I have tried somthing like: struct input { int a; float b,c; } struct input* readData(char *filename,int *size); int main() { return 0; } struct input* readData(char *filename,int *size) { char filename[] = "input.txt"; FILE *fp = fopen(filename, "r"); int num; while(!feof(fp)) { fscanf(fp,"%f", &num); struct input *arr = (struct input*)malloc(sizeof(struct input)); } }

    Read the article

  • Wrapping malloc - C

    - by Appu
    I am a beginner in C. While reading git's source code, I found this wrapper function around malloc. void *xmalloc(size_t size) { void *ret = malloc(size); if (!ret && !size) ret = malloc(1); if (!ret) { release_pack_memory(size, -1); ret = malloc(size); if (!ret && !size) ret = malloc(1); if (!ret) die("Out of memory, malloc failed"); } #ifdef XMALLOC_POISON memset(ret, 0xA5, size); #endif return ret; } Questions I couldn't understand why are they using malloc(1)? What does release_pack_memory does and I can't find this functions implementation in the whole source code. What does the #ifdef XMALLOC_POISON memset(ret, 0xA5, size); does? I am planning to reuse this function on my project. Is this a good wrapper around malloc? Any help would be great.

    Read the article

  • calloc v/s malloc and time efficiency

    - by yCalleecharan
    Hi, I've read with interest the post "c difference between malloc and calloc". I'm using malloc in my code and would like to know what difference I'll have using calloc instead. My present (pseudo)code with malloc: Scenario 1 int main() { allocate large arrays with malloc INITIALIZE ALL ARRAY ELEMENTS TO ZERO for loop //say 1000 times do something and write results to arrays end for loop FREE ARRAYS with free command } //end main If I use calloc instead of malloc, then I'll have: Scenario2 int main() { for loop //say 1000 times ALLOCATION OF ARRAYS WITH CALLOC do something and write results to arrays FREE ARRAYS with free command end for loop } //end main I have three questions: Which of the scenarios is more efficient if the arrays are very large? Which of the scenarios will be more time efficient if the arrays are very large? In both scenarios,I'm just writing to arrays in the sense that for any given iteration in the for loop, I'm writing each array sequentially from the first element to the last element. The important question: If I'm using malloc as in scenario 1, then is it necessary that I initialize the elements to zero? Say with malloc I have array z = [garbage1, garbage2, garbage 3]. For each iteration, I'm writing elements sequentially i.e. in the first iteration I get z =[some_result, garbage2, garbage3], in the second iteration I get in the first iteration I get z =[some_result, another_result, garbage3] and so on, then do I need specifically to initialize my arrays after malloc?

    Read the article

  • Malloc corrupting already malloc'd memory in C

    - by Kyte
    I'm currently helping a friend debug a program of his, which includes linked lists. His list structure is pretty simple: typedef struct nodo{ int cantUnos; char* numBin; struct nodo* sig; }Nodo; We've got the following code snippet: void insNodo(Nodo** lista, char* auxBin, int auxCantUnos){ printf("*******Insertando\n"); int i; if (*lista) printf("DecInt*%p->%p\n", *lista, (*lista)->sig); Nodo* insert = (Nodo*)malloc(sizeof(Nodo*)); if (*lista) printf("Malloc*%p->%p\n", *lista, (*lista)->sig); insert->cantUnos = auxCantUnos; insert->numBin = (char*)malloc(strlen(auxBin)*sizeof(char)); for(i=0 ; i<strlen(auxBin) ; i++) insert->numBin[i] = auxBin[i]; insert-numBin[i] = '\0'; insert-sig = NULL; Nodo* aux; [etc] (The lines with extra indentation were my addition for debug purposes) This yields me the following: *******Insertando DecInt*00341098->00000000 Malloc*00341098->2832B6EE (*lista)-sig is previously and deliberately set as NULL, which checks out until here, and fixed a potential buffer overflow (he'd forgotten to copy the NULL-terminator in insert-numBin). I can't think of a single reason why'd that happen, nor I've got any idea on what else should I provide as further info. (Compiling on latest stable MinGW under fully-patched Windows 7, friend's using MinGW under Windows XP. On my machine, at least, in only happens when GDB's not attached.) Any ideas? Suggestions? Possible exorcism techniques? (Current hack is copying the sig pointer to a temp variable and restore it after malloc. It breaks anyways. Turns out the 2nd malloc corrupts it too. Interestingly enough, it resets sig to the exact same value as the first one).

    Read the article

  • c programming malloc question

    - by user535256
    Hello guys, Just got query regarding c malloc() function. I am read()ing x number of bytes from a file to get lenght of filename, like ' read(file, &namelen, sizeof(unsigned char)); ' . The variable namelen is a type unsigned char and was written into file as that type (1 byte). Now namelen has the lenght of filename ie namelen=8 if file name was 'data.txt', plus extra /0 at end, that working fine. Now I have a structure recording file info, ie filename, filelenght, content size etc. struct fileinfo { char *name; ...... other variable like size etc }; struct fileinfo *files; Question: I want to make that files.name variable the size of namelen ie 8 so I can successfully write the filename into it, like ' files[i].name = malloc(namelen) ' However, I dont want it to be malloc(sizeof(namelen)) as that would make it file.name[1] as the size of its type unsigned char. I want it to be the value thats stored inside variable &namelen ie 8 so file.name[8] so data.txt can be read() from file as 8 bytes and written straight into file.name[8? Is there a way to do this my current code is this and returns 4 not 8 files[i].name = malloc(namelen); //strlen(files[i].name) - returns 4 //perhaps something like malloc(sizeof(&namelen)) but does not work Thanks for any suggestions Have tried suggested suggestions guys, but I now get a segmentation fault error using: printf("\nsizeofnamelen=%x\n",namelen); //gives 8 for data.txt files[i].name = malloc(namelen + 1); read(file, &files[i].name, namelen); int len=strlen(files[i].name); printf("\nnamelen=%d",len); printf("\nname=%s\n",files[i].name); When I try to open() file with that files[i].name variable it wont open so the data does not appear to be getting written inside the read() &files[i].name and strlen() causes segemntation error as well as trying to print the filename

    Read the article

  • C malloc assertion help

    - by Chris
    I am implementing a divide and conquer polynomial algorithm so i can bench it against an opencl implementation, but i can't seem to get malloc to work. When I run the program it allocates a bunch of stuff, checks some things, then sends the size/2 to the algorithm. Then when I hit the malloc line again it spits out this: malloc.c:3096: sYSMALLOc: Assertion `(old_top == (((mbinptr) (((char *) &((av)-bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) = (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 * (sizeof(size_t))) - 1)) & ~((2 * (sizeof(size_t))) - 1))) && ((old_top)-size & 0x1) && ((unsigned long)old_end & pagemask) == 0)' failed. Aborted The line in question is: int *out, .....other vars....; out = (int *)malloc(sizeof(int) * size * 2); I have checked size with fprintf and it is a positive int (usually 50 at that point). I have tried calling malloc with a plain number as well and i still get the error. I'm just stumped at what's going on, and nothing from google that I have found so far has been too helpful. Any ideas what's going on? I'm trying to figure out how to compile a newer GCC in case it's a compiler error, but i really doubt it.

    Read the article

  • why malloc+memset slower than calloc?

    - by kingkai
    It's known that calloc differentiates itself with malloc in which it initializes the memory alloted. With calloc, the memory is set to zero. With malloc, the memory is not cleared. So in everyday work, i regard calloc as malloc+memset. Incidentally, for fun, i wrote the following codes for benchmark. The result is confused. Code 1: #include<stdio.h> #include<stdlib.h> #define BLOCK_SIZE 1024*1024*256 int main() { int i=0; char *buf[10]; while(i<10) { buf[i] = (char*)calloc(1,BLOCK_SIZE); i++; } } time ./a.out real 0m0.287s user 0m0.095s sys 0m0.192s Code 2: #include<stdio.h> #include<stdlib.h> #include<string.h> #define BLOCK_SIZE 1024*1024*256 int main() { int i=0; char *buf[10]; while(i<10) { buf[i] = (char*)malloc(BLOCK_SIZE); memset(buf[i],'\0',BLOCK_SIZE); i++; } } time ./a.out real 0m2.693s user 0m0.973s sys 0m1.721s Repalce memset with bzero(buf[i],BLOCK_SIZE) in Code 2 produce the result alike. My Question is that why malloc+memset is so much slower than calloc? How can calloc do that ? Thanks!

    Read the article

  • Malloc function in C++

    - by Mohit Deshpande
    I am transitioning to C++ from C. In C++, is there any use for the malloc function? Or can I just declare it with the "new" keyword. For example: class Node { ... } ... Node *node1 = malloc(sizeof(Node)); //malloc Node *node2 = new Node; //new Which one should I use?

    Read the article

  • maximum memory which malloc can allocate!

    - by Vikas
    I was trying to figure out how much memory I can malloc to maximum extent on my machine (1 Gb RAM 160 Gb HD Windows platform). I read that maximum memory malloc can allocate is limited to physical memory.(on heap) Also when a program exceeds consumption of memory to a certain level, the computer stops working because other applications do not get enough memory that they require. So to confirm,I wrote a small program in C, int main(){ int *p; while(1){ p=(int *)malloc(4); if(!p)break; } } Hoping that there would be a time when memory allocation will fail and loop will be breaked. But my computer hanged as It was an infinite loop. I waited for about an hour and finally I had to forcely shut down my computer. Some questions: Does malloc allocate memory from HD also? What was the reason for above behaviour? Why didn't loop breaked at any point of time.? Why wasn't there any allocation failure?

    Read the article

  • iphone memory leaks and malloc?

    - by Brodie4598
    Okay so im finally to the point where I am testing my iPad App on an actual iPad... One thing that my app does is display a large (2mb) image in a scroll view. This is causing the iPad to get memory warnings. I run the app in the instruments to check for the leak. When I load the image, a leak is detected and i see the following in the allocations: ALl Allocations: 83.9 MB Malloc 48.55 MB: 48.55 MB Malloc 34.63 MB: 34.63 MB What im trying to understand is how to plug the leak obviously, but also why a 2MB image is causing a malloc of 20x that size I am very new to programming in obj-c so im sure this is an obvious thing, but I just cant figure it out. Here is the code:

    Read the article

  • C: Expanding an array with malloc

    - by Mal Ock
    I'm a bit new to malloc and C in general. I wanted to know how I can, if needed, extend the size of an otherwise fixed-size array with malloc. Example: #define SIZE 1000 struct mystruct { int a; int b; char c; }; mystruct myarray[ SIZE ]; int myarrayMaxSize = SIZE; .... if ( i > myarrayMaxSize ) { // malloc another SIZE (1000) elements myarrayMaxSize += SIZE; } The above example should make clear what I want to accomplish. (By the way: I need this for an interpreter I write: Work with a fixed amount of variables and in case more are needed, just allocate them dynamically)

    Read the article

  • Does malloc() allocate a contiguous block of memory?

    - by user66854
    I have a piece of code written by a very old school programmer :-) . it goes something like this typedef struct ts_request { ts_request_buffer_header_def header; char package[1]; } ts_request_def; ts_request_buffer_def* request_buffer = malloc(sizeof(ts_request_def) + (2 * 1024 * 1024)); the programmer basically is working on a buffer overflow concept. I know the code looks dodgy. so my questions are: Does malloc always allocate contiguous block of memory ?. because in this code if the blocks are not contiguous , the code will fail big time Doing free(request_buffer) , will it free all the bytes allocated by malloc i.e sizeof(ts_request_def) + (2 * 1024 * 1024), or only the bytes of the size of the structure sizeof(ts_request_def) Do you see any evident problems with this approach , i need to discuss this with my boss and would like to point out any loopholes with this approach

    Read the article

  • Is it secure to use malloc?

    - by Felix Guerrero
    Somebody told me that allocating with malloc is not secure anymore, I'm not a C/C++ guru but I've made some stuff with malloc and C/C++. Does anyone know about what risks I'm into? Quoting him: [..] But indeed the weak point of C/C++ it is the security, and the Achilles' heel is indeed malloc and the abuse of pointers. C/C++ it is a well known insecure language. [..] There would be few apps in what I would not recommend to continue programming with C++."

    Read the article

  • SDCC and malloc() - allocating much less memory than is available

    - by Duncan Bayne
    When I run compile this code with SDCC 3.1.0, and run it on an Amstrad CPC 464 (under emulation, with WinCPC 0.9.26 running on Wine): void _test_malloc() { long idx = 0; while (1) { if (malloc(5)) { printf("%ld\r\n", ++idx); } else { printf("done"); break; } } } ... it consistently taps out at 92 malloc()s. I make that 460 bytes, which leads me to a couple of questions: What is malloc() doing on this system? I was sort of hoping for an order of magnitude more storage even on a 64kB system The behaviour is consistent on 64kB systems and 128kB systems; do I have to perform some sort of magic to access the additional memory, like manual bank switching?

    Read the article

  • I want to make my own Malloc

    - by Unknown
    I want to make my own malloc/free so I can make a precise copying allocator. Any gurus have any tips and suggestions? I have a few questions for now: Should I just malloc large chunks of memory, and then distribute from that so I don't have to call the system calls? How are copying collectors usually done? I would imagine that this part is a bit complicated to do efficiently. My naive implementation would just malloc a block the size of the remaining objects which would require 2x the space.

    Read the article

  • C program runs in Cygwin but not Linux (Malloc)

    - by Shawn
    I have a heap allocation error that I cant spot in my code that is picked up on vanguard/gdb on Linux but runs perfectly on a Windows cygwin environment. I understand that Linux could be tighter with its heap allocation than Windows but I would really like to have a response that discovers the issue/possible fix. I'm also aware that I shouldn't typecast malloc in C but it's a force of habit and doesn't change my problem from happening. My program actually compiles without error on both Linux & Windows but when I run it in Linux I get a scary looking result: malloc.c:3074: sYSMALLOc: Assertion `(old_top == (((mbinptr) (((char *) &((av)-bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) = (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 * (sizeof(size_t))) - 1)) & ~((2 * (sizeof(size_t))) - 1))) && ((old_top)-size & 0x1) && ((unsigned long)old_end & pagemask) == 0)' failed. Aborted Attached snippet from my code that is being pointed to as the error for review: /* Main */ int main(int argc, char * argv[]) { FILE *pFile; unsigned char *buffer; long int lSize; pFile = fopen ( argv[1] , "r" ); if (pFile==NULL) {fputs ("File error on arg[1]",stderr); return 1;} fseek (pFile , 0 , SEEK_END); lSize = ftell (pFile); rewind (pFile); buffer = (char*) malloc(sizeof(char) * lSize+1); if (buffer == NULL) {fputs ("Memory error",stderr); return 2;} bitpair * ppairs = (bitpair *) malloc(sizeof(bitpair) * (lSize+1)); //line 51 below calcpair(ppairs, (lSize+1)); /* irrelevant stuff */ fclose(pFile); free(buffer); free(ppairs); } typedef struct { long unsigned int a; //not actual variable names... Yes I need them to be long unsigned long unsigned int b; long unsigned int c; long unsigned int d; long unsigned int e; } bitpair; void calcpair(bitpair * ppairs, long int bits); void calcPairs(bitpair * ppairs, long int bits) { long int i, top, bot, var_1, var_2; int count = 0; for(i = 0; i < cs; i++) { top = 0; ppairs[top].e = 1; do { bot = count; count++; } while(ppairs[bot].e != 0); ppairs[bot].e = 1; var_1 = bot; var_2 = top; calcpair * bp = &ppairs[var_2]; bp->a = var_2; bp->b = var_1; bp->c = i; bp = &ppairs[var_1]; bp->a = var_2; bp->b = var_1; bp->c = i; } return; } gdb reports: free(): invalid pointer: 0x0000000000603290 * valgrind reports the following message 5 times before exiting due to "VALGRIND INTERNAL ERROR" signal 11 (SIGSEGV): Invalid read of size 8 ==2727== at 0x401043: calcPairs (in /home/user/Documents/5-3/ubuntu test/main) ==2727== by 0x400C9A: main (main.c:51) ==2727== Address 0x5a607a0 is not stack'd, malloc'd or (recently) free'd

    Read the article

  • malloc and delete in C++, opinions

    - by Alexander
    In C++ using delete to free memory obtained with malloc() doesn't necessarily cause a program to blow up. Do you guys think a warning or perhaps even an assertion failure should be produced if delete is used to free memory obtained using malloc()?? Why do you think that Stroustrup did not had this feature on C++?

    Read the article

  • Help with malloc and free: Glibc detected: free(): invalid pointer

    - by nunos
    I need help with debugging this piece of code. I know the problem is in malloc and free but can't find exactly where, why and how to fix it. Please don't answer: "Use gdb" and that's it. I would use gdb to debug it, but I still don't know much about it and am still learning it, and would like to have, in the meanwhile, another solution. Thanks. #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <unistd.h> #include <string.h> #include <sys/wait.h> #include <sys/types.h> #define MAX_COMMAND_LENGTH 256 #define MAX_ARGS_NUMBER 128 #define MAX_HISTORY_NUMBER 100 #define PROMPT ">>> " int num_elems; typedef enum {false, true} bool; typedef struct { char **arg; char *infile; char *outfile; int background; } Command_Info; int parse_cmd(char *cmd_line, Command_Info *cmd_info) { char *arg; char *args[MAX_ARGS_NUMBER]; int i = 0; arg = strtok(cmd_line, " "); while (arg != NULL) { args[i] = arg; arg = strtok(NULL, " "); i++; } num_elems = i;precisa em free_mem if (num_elems == 0) return 0; cmd_info->arg = (char **) ( malloc(num_elems * sizeof(char *)) ); cmd_info->infile = NULL; cmd_info->outfile = NULL; cmd_info->background = 0; bool b_infile = false; bool b_outfile = false; int iarg = 0; for (i = 0; i < num_elems; i++) { if ( !strcmp(args[i], "<") ) { if ( b_infile || i == num_elems-1 || !strcmp(args[i+1], "<") || !strcmp(args[i+1], ">") || !strcmp(args[i+1], "&") ) return -1; i++; cmd_info->infile = malloc(strlen(args[i]) * sizeof(char)); strcpy(cmd_info->infile, args[i]); b_infile = true; } else if (!strcmp(args[i], ">")) { if ( b_outfile || i == num_elems-1 || !strcmp(args[i+1], ">") || !strcmp(args[i+1], "<") || !strcmp(args[i+1], "&") ) return -1; i++; cmd_info->outfile = malloc(strlen(args[i]) * sizeof(char)); strcpy(cmd_info->outfile, args[i]); b_outfile = true; } else if (!strcmp(args[i], "&")) { if ( i == 0 || i != num_elems-1 || cmd_info->background ) return -1; cmd_info->background = true; } else { cmd_info->arg[iarg] = malloc(strlen(args[i]) * sizeof(char)); strcpy(cmd_info->arg[iarg], args[i]); iarg++; } } cmd_info->arg[iarg] = NULL; return 0; } void print_cmd(Command_Info *cmd_info) { int i; for (i = 0; cmd_info->arg[i] != NULL; i++) printf("arg[%d]=\"%s\"\n", i, cmd_info->arg[i]); printf("arg[%d]=\"%s\"\n", i, cmd_info->arg[i]); printf("infile=\"%s\"\n", cmd_info->infile); printf("outfile=\"%s\"\n", cmd_info->outfile); printf("background=\"%d\"\n", cmd_info->background); } void get_cmd(char* str) { fgets(str, MAX_COMMAND_LENGTH, stdin); str[strlen(str)-1] = '\0'; } pid_t exec_simple(Command_Info *cmd_info) { pid_t pid = fork(); if (pid < 0) { perror("Fork Error"); return -1; } if (pid == 0) { if ( (execvp(cmd_info->arg[0], cmd_info->arg)) == -1) { perror(cmd_info->arg[0]); exit(1); } } return pid; } void type_prompt(void) { printf("%s", PROMPT); } void syntax_error(void) { printf("msh syntax error\n"); } void free_mem(Command_Info *cmd_info) { int i; for (i = 0; cmd_info->arg[i] != NULL; i++) free(cmd_info->arg[i]); free(cmd_info->arg); free(cmd_info->infile); free(cmd_info->outfile); } int main(int argc, char* argv[]) { char cmd_line[MAX_COMMAND_LENGTH]; Command_Info cmd_info; //char* history[MAX_HISTORY_NUMBER]; while (true) { type_prompt(); get_cmd(cmd_line); if ( parse_cmd(cmd_line, &cmd_info) == -1) { syntax_error(); continue; } if (!strcmp(cmd_line, "")) continue; if (!strcmp(cmd_info.arg[0], "exit")) exit(0); pid_t pid = exec_simple(&cmd_info); waitpid(pid, NULL, 0); free_mem(&cmd_info); } return 0; }

    Read the article

  • malloc: error checking and freeing memory

    - by yCalleecharan
    Hi, I'm using malloc to make an error check of whether memory can be allocated or not for the particular array z1. ARRAY_SIZE is a predefined with a numerical value. I use casting as I've read it's safe to do so. long double *z1 = (long double *)malloc(sizeof (long double) * ARRAY_SIZE); if(z1 == NULL){ printf("Out of memory\n"); exit(-1); } The above is just a snippet of my code, but when I add the error checking part (contained in the if statement above), I get a lot of compile time errors with visual studio 2008. It is this error checking part that's generating all the errors. What am I doing wrong? On a related issue with malloc, I understand that the memory needs to be deallocated/freed after the variable/array z1 has been used. For the array z1, I use: free(z1); z1 = NULL; Is the second line z1 = NULL necessary? Thanks a lot...

    Read the article

  • Multidimensional array with unequal second dimension size using malloc()

    - by user288422
    Hello, I am playing around with multidimensional array of unequal second dimension size. Lets assume that I need the following data structure: [&ptr0]-[0][1][2][3][4][5][6][7][8][9] [&ptr1]-[0][1][2] [&ptr2]-[0][1][2][3][4] int main() { int *a[3]; int *b; int i; a[0] = (int *)malloc(10 * sizeof(int)); a[1] = (int *)malloc(2 * sizeof(int)); a[2] = (int *)malloc(4 * sizeof(int)); for(i=0; i<10; i++) a[0][i]=i; for(i=0; i<2; i++) a[1][i]=i; for(i=0; i<4; i++) a[2][i]=i; } I did some tests and it seems like I can store a value at a[1][3]. Does it mean that rows in my array are of equal size 10?

    Read the article

  • C Programming: malloc() inside another function

    - by vikramtheone
    Hi Guys, I need help with malloc() inside another function. I'm passing a pointer and size to the function from my main() and I would like to allocate memory for that pointer dynamically using malloc() from inside that called function, but what I see is that.... the memory which is getting allocated is for the pointer declared withing my called function and not for the pointer which is inside the main(). How should I pass a pointer to a function and allocate memory for the passed pointer from inside the called function? Can anyone throw light on this? Help!!! Vikram I have written the following code and I get the output as shown below SOURCE: main() { unsigned char *input_image; unsigned int bmp_image_size = 262144; if(alloc_pixels(input_image, bmp_image_size)==NULL) printf("\nPoint2: Memory allocated: %d bytes",_msize(input_image)); else printf("\nPoint3: Memory not allocated"); } signed char alloc_pixels(unsigned char *ptr, unsigned int size) { signed char status = NO_ERROR; ptr = NULL; ptr = (unsigned char*)malloc(size); if(ptr== NULL) { status = ERROR; free(ptr); printf("\nERROR: Memory allocation did not complete successfully!"); } printf("\nPoint1: Memory allocated: %d bytes",_msize(ptr)); return status; } PROGRAM OUTPUT: Point1: Memory allocated ptr: 262144 bytes Point2: Memory allocated input_image: 0 bytes

    Read the article

  • c++ malloc segment fault

    - by chnet
    I have a problem about malloc(). It is wired. 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

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