Search Results

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

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

  • What does the Sys_PageIn() function do in Quake?

    - by Philip
    I've noticed in the initialization process of the original Quake the following function is called. volatile int sys_checksum; // **lots of code** void Sys_PageIn(void *ptr, int size) { byte *x; int j,m,n; //touch all memory to make sure its there. The 16-page skip is to //keep Win 95 from thinking we're trying to page ourselves in (we are //doing that, of course, but there's no reason we shouldn't) x = (byte *)ptr; for (n=0 ; n<4 ; n++) { for (m=0; m<(size - 16 * 0x1000) ; m += 4) { sys_checksum += *(int *)&x[m]; sys_checksum += *(int *)&x[m + 16 * 0x10000]; } } } I think I'm just not familiar enough with paging to understand this function. the void* ptr passed to the function is a recently malloc()'d piece of memory that is size bytes big. This is the whole function - j is an unreferenced variable. My best guess is that the volatile int sys_checksum is forcing the system to physically read all of the space that was just malloc()'d, perhaps to ensure that these spaces exist in virtual memory? Is this right? And why would someone do this? Is it for some antiquated Win95 reason?

    Read the article

  • push_back of STL list got bad performance?

    - by Leon Zhang
    I wrote a simple program to test STL list performance against a simple C list-like data structure. It shows bad performance at "push_back()" line. Any comments on it? $ ./test2 Build the type list : time consumed -> 0.311465 Iterate over all items: time consumed -> 0.00898 Build the simple C List: time consumed -> 0.020275 Iterate over all items: time consumed -> 0.008755 The source code is: #include <stdexcept> #include "high_resolution_timer.hpp" #include <list> #include <algorithm> #include <iostream> #define TESTNUM 1000000 /* The test struct */ struct MyType { int num; }; /* * C++ STL::list Test */ typedef struct MyType* mytype_t; void myfunction(mytype_t t) { } int test_stl_list() { std::list<mytype_t> mylist; util::high_resolution_timer t; /* * Build the type list */ t.restart(); for(int i = 0; i < TESTNUM; i++) { mytype_t aItem = (mytype_t) malloc(sizeof(struct MyType)); if(aItem == NULL) { printf("Error: while malloc\n"); return -1; } aItem->num = i; mylist.push_back(aItem); } std::cout << " Build the type list : time consumed -> " << t.elapsed() << std::endl; /* * Iterate over all item */ t.restart(); std::for_each(mylist.begin(), mylist.end(), myfunction); std::cout << " Iterate over all items: time consumed -> " << t.elapsed() << std::endl; return 0; } /* * a simple C list */ struct MyCList; struct MyCList{ struct MyType m; struct MyCList* p_next; }; int test_simple_c_list() { struct MyCList* p_list_head = NULL; util::high_resolution_timer t; /* * Build it */ t.restart(); struct MyCList* p_new_item = NULL; for(int i = 0; i < TESTNUM; i++) { p_new_item = (struct MyCList*) malloc(sizeof(struct MyCList)); if(p_new_item == NULL) { printf("ERROR : while malloc\n"); return -1; } p_new_item->m.num = i; p_new_item->p_next = p_list_head; p_list_head = p_new_item; } std::cout << " Build the simple C List: time consumed -> " << t.elapsed() << std::endl; /* * Iterate all items */ t.restart(); p_new_item = p_list_head; while(p_new_item->p_next != NULL) { p_new_item = p_new_item->p_next; } std::cout << " Iterate over all items: time consumed -> " << t.elapsed() << std::endl; return 0; } int main(int argc, char** argv) { if(test_stl_list() != 0) { printf("ERROR: error at testcase1\n"); return -1; } if(test_simple_c_list() != 0) { printf("ERROR: error at testcase2\n"); return -1; } return 0; }

    Read the article

  • Why can't I assign a scalar value to a class using shorthand, but instead declare it first, then set

    - by ~delan-azabani
    I am writing a UTF-8 library for C++ as an exercise as this is my first real-world C++ code. So far, I've implemented concatenation, character indexing, parsing and encoding UTF-8 in a class called "ustring". It looks like it's working, but two (seemingly equivalent) ways of declaring a new ustring behave differently. The first way: ustring a; a = "test"; works, and the overloaded "=" operator parses the string into the class (which stores the Unicode strings as an dynamically allocated int pointer). However, the following does not work: ustring a = "test"; because I get the following error: test.cpp:4: error: conversion from ‘const char [5]’ to non-scalar type ‘ustring’ requested Is there a way to workaround this error? It probably is a problem with my code, though. The following is what I've written so far for the library: #include <cstdlib> #include <cstring> class ustring { int * values; long len; public: long length() { return len; } ustring * operator=(ustring input) { len = input.len; values = (int *) malloc(sizeof(int) * len); for (long i = 0; i < len; i++) values[i] = input.values[i]; return this; } ustring * operator=(char input[]) { len = sizeof(input); values = (int *) malloc(0); long s = 0; // s = number of parsed chars int a, b, c, d, contNeed = 0, cont = 0; for (long i = 0; i < sizeof(input); i++) if (input[i] < 0x80) { // ASCII, direct copy (00-7f) values = (int *) realloc(values, sizeof(int) * ++s); values[s - 1] = input[i]; } else if (input[i] < 0xc0) { // this is a continuation (80-bf) if (cont == contNeed) { // no need for continuation, use U+fffd values = (int *) realloc(values, sizeof(int) * ++s); values[s - 1] = 0xfffd; } cont = cont + 1; values[s - 1] = values[s - 1] | ((input[i] & 0x3f) << ((contNeed - cont) * 6)); if (cont == contNeed) cont = contNeed = 0; } else if (input[i] < 0xc2) { // invalid byte, use U+fffd (c0-c1) values = (int *) realloc(values, sizeof(int) * ++s); values[s - 1] = 0xfffd; } else if (input[i] < 0xe0) { // start of 2-byte sequence (c2-df) contNeed = 1; values = (int *) realloc(values, sizeof(int) * ++s); values[s - 1] = (input[i] & 0x1f) << 6; } else if (input[i] < 0xf0) { // start of 3-byte sequence (e0-ef) contNeed = 2; values = (int *) realloc(values, sizeof(int) * ++s); values[s - 1] = (input[i] & 0x0f) << 12; } else if (input[i] < 0xf5) { // start of 4-byte sequence (f0-f4) contNeed = 3; values = (int *) realloc(values, sizeof(int) * ++s); values[s - 1] = (input[i] & 0x07) << 18; } else { // restricted or invalid (f5-ff) values = (int *) realloc(values, sizeof(int) * ++s); values[s - 1] = 0xfffd; } return this; } ustring operator+(ustring input) { ustring result; result.len = len + input.len; result.values = (int *) malloc(sizeof(int) * result.len); for (long i = 0; i < len; i++) result.values[i] = values[i]; for (long i = 0; i < input.len; i++) result.values[i + len] = input.values[i]; return result; } ustring operator[](long index) { ustring result; result.len = 1; result.values = (int *) malloc(sizeof(int)); result.values[0] = values[index]; return result; } char * encode() { char * r = (char *) malloc(0); long s = 0; for (long i = 0; i < len; i++) { if (values[i] < 0x80) r = (char *) realloc(r, s + 1), r[s + 0] = char(values[i]), s += 1; else if (values[i] < 0x800) r = (char *) realloc(r, s + 2), r[s + 0] = char(values[i] >> 6 | 0x60), r[s + 1] = char(values[i] & 0x3f | 0x80), s += 2; else if (values[i] < 0x10000) r = (char *) realloc(r, s + 3), r[s + 0] = char(values[i] >> 12 | 0xe0), r[s + 1] = char(values[i] >> 6 & 0x3f | 0x80), r[s + 2] = char(values[i] & 0x3f | 0x80), s += 3; else r = (char *) realloc(r, s + 4), r[s + 0] = char(values[i] >> 18 | 0xf0), r[s + 1] = char(values[i] >> 12 & 0x3f | 0x80), r[s + 2] = char(values[i] >> 6 & 0x3f | 0x80), r[s + 3] = char(values[i] & 0x3f | 0x80), s += 4; } return r; } };

    Read the article

  • Figuring Out Memory Leaks without Clang

    - by RoLYroLLs
    I'm trying to see if I can find some leaks myself in Apple's TopSongs app. Can someone help me out in at least one and how to identify what is in the Leaks reports and how I can get an idea on finding them? ie: I got one like this: # Category Event Type Timestamp Address Size Responsible Library Responsible Caller 0 GeneralBlock-448 Malloc 00:02.185 0x3f41220 448 libxml2.2.dylib xmlNewParserCtxt From what I can tell, the method xmlNewParserCtxt is the problem, and it's not releasing an object, hence Malloc. The responsible library tells me it's the libxml2.2.dylib library with the problem, which I can't edit. Am I heading in the right direction? If so, half the leaks are in that library and well, i can't edit that.

    Read the article

  • CUDA: cudaMemcpy only works in emulation mode.

    - by Jason
    I am just starting to learn how to use CUDA. I am trying to run some simple example code: float *ah, *bh, *ad, *bd; ah = (float *)malloc(sizeof(float)*4); bh = (float *)malloc(sizeof(float)*4); cudaMalloc((void **) &ad, sizeof(float)*4); cudaMalloc((void **) &bd, sizeof(float)*4); ... initialize ah ... /* copy array on device */ cudaMemcpy(ad,ah,sizeof(float)*N,cudaMemcpyHostToDevice); cudaMemcpy(bd,ad,sizeof(float)*N,cudaMemcpyDeviceToDevice); cudaMemcpy(bh,bd,sizeof(float)*N,cudaMemcpyDeviceToHost); When I run in emulation mode (nvcc -deviceemu) it runs fine (and actually copies the array). But when I run it in regular mode, it runs w/o error, but never copies the data. It's as if the cudaMemcpy lines are just ignored. What am I doing wrong? Thank you very much, Jason

    Read the article

  • Problem using void pointer as a function argument

    - by Nazgulled
    Hi, I can't understand this result... The code: void foo(void * key, size_t key_sz) { HashItem *item = malloc(sizeof(HashItem)); printf("[%d]\n", (int)key); ... item->key = malloc(key_sz); memcpy(item->key, key, key_sz); } void bar(int num) { foo(&num, sizeof(int)); } And I do this call: bar(900011009); But the printf() output is: [-1074593956] I really need key to be a void pointer, how can I fix this?

    Read the article

  • Help debugging c fifos code - stack smashing detected - open call not functioning - removing pipes

    - by nunos
    I have three bugs/questions regarding the source code pasted below: stack smashing deteced: In order to compile and not have that error I have addedd the gcc compile flag -fno-stack-protector. However, this should be just a temporary solution, since I would like to find where the cause for this is and correct it. However, I haven't been able to do so. Any clues? For some reason, the last open function call doesn't work and the programs just stops there, without an error, even though the fifo already exists. I want to delete the pipes from the filesystem after before terminating the processes. I have added close and unlink statements at the end, but the fifos are not removed. What am I doing wrong? Thanks very much in advance. P.S.: I am pasting here the whole source file for additional clarity. Just ignore the comments, since they are in my own native language. server.c: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #define MAX_INPUT_LENGTH 100 #define FIFO_NAME_MAX_LEN 20 #define FIFO_DIR "/tmp/" #define FIFO_NAME_CMD_CLI_TO_SRV "lrc_cmd_cli_to_srv" typedef enum { false, true } bool; bool background = false; char* logfile = NULL; void read_from_fifo(int fd, char** var) { int n_bytes; read(fd, &n_bytes, sizeof(int)); *var = (char *) malloc (n_bytes); read(fd, *var, n_bytes); printf("read %d bytes '%s'\n", n_bytes, *var); } void write_to_fifo(int fd, char* data) { int n_bytes = (strlen(data)+1) * sizeof(char); write(fd, &n_bytes, sizeof(int)); //primeiro envia o numero de bytes que a proxima instrucao write ira enviar write(fd, data, n_bytes); printf("writing %d bytes '%s'\n", n_bytes, data); } int main(int argc, char* argv[]) { //CRIA FIFO CMD_CLI_TO_SRV, se ainda nao existir char* fifo_name_cmd_cli_to_srv; fifo_name_cmd_cli_to_srv = (char*) malloc ( (strlen(FIFO_NAME_CMD_CLI_TO_SRV) + strlen(FIFO_DIR) + 1) * sizeof(char) ); strcpy(fifo_name_cmd_cli_to_srv, FIFO_DIR); strcat(fifo_name_cmd_cli_to_srv, FIFO_NAME_CMD_CLI_TO_SRV); int n = mkfifo(fifo_name_cmd_cli_to_srv, 0660); //TODO ver permissoes if (n < 0 && errno != EEXIST) //se houver erro, e nao for por causa de ja haver um com o mesmo nome, termina o programa { fprintf(stderr, "erro ao criar o fifo\n"); fprintf(stderr, "errno: %d\n", errno); exit(4); } //se por acaso já existir, nao cria o fifo e continua o programa normalmente //le informacao enviada pelo cliente, nesta ordem: //1. pid (em formato char*) do processo cliente //2. comando /CONNECT //3. nome de fifo INFO_SRV_TO_CLIXXX //4. nome de fifo MSG_SRV_TO_CLIXXX char* command; char* fifo_name_info_srv_to_cli; char* fifo_name_msg_srv_to_cli; char* client_pid_string; int client_pid; int fd_cmd_cli_to_srv, fd_info_srv_to_cli; fd_cmd_cli_to_srv = open(fifo_name_cmd_cli_to_srv, O_RDONLY); read_from_fifo(fd_cmd_cli_to_srv, &client_pid_string); client_pid = atoi(client_pid_string); read_from_fifo(fd_cmd_cli_to_srv, &command); //recebe commando /CONNECT read_from_fifo(fd_cmd_cli_to_srv, &fifo_name_info_srv_to_cli); //recebe nome de fifo INFO_SRV_TO_CLIXXX read_from_fifo(fd_cmd_cli_to_srv, &fifo_name_msg_srv_to_cli); //recebe nome de fifo MSG_TO_SRV_TO_CLIXXX //CIRA FIFO MSG_CLIXXX_TO_SRV char fifo_name_msg_cli_to_srv[FIFO_NAME_MAX_LEN]; strcpy(fifo_name_msg_cli_to_srv, FIFO_DIR); strcat(fifo_name_msg_cli_to_srv, "lrc_msg_cli"); strcat(fifo_name_msg_cli_to_srv, client_pid_string); strcat(fifo_name_msg_cli_to_srv, "_to_srv"); n = mkfifo(fifo_name_msg_cli_to_srv, 0660); if (n < 0) { fprintf(stderr, "error creating %s\n", fifo_name_msg_cli_to_srv); fprintf(stderr, "errno: %d\n", errno); exit(5); } //envia ao cliente a resposta ao commando /CONNECT fd_info_srv_to_cli = open(fifo_name_info_srv_to_cli, O_WRONLY); write_to_fifo(fd_info_srv_to_cli, fifo_name_msg_cli_to_srv); free(logfile); free(fifo_name_cmd_cli_to_srv); close(fd_cmd_cli_to_srv); unlink(fifo_name_cmd_cli_to_srv); unlink(fifo_name_msg_cli_to_srv); unlink(fifo_name_msg_srv_to_cli); unlink(fifo_name_info_srv_to_cli); printf("fim\n"); return 0; } client.c: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #define MAX_INPUT_LENGTH 100 #define PID_BUFFER_LEN 10 #define FIFO_NAME_CMD_CLI_TO_SRV "lrc_cmd_cli_to_srv" #define FIFO_NAME_INFO_SRV_TO_CLI "lrc_info_srv_to_cli" #define FIFO_NAME_MSG_SRV_TO_CLI "lrc_msg_srv_to_cli" #define COMMAND_MAX_LEN 100 #define FIFO_DIR "/tmp/" typedef enum { false, true } bool; char* nickname; char* name; char* email; void write_to_fifo(int fd, char* data) { int n_bytes = (strlen(data)+1) * sizeof(char); write(fd, &n_bytes, sizeof(int)); //primeiro envia o numero de bytes que a proxima instrucao write ira enviar write(fd, data, n_bytes); printf("writing %d bytes '%s'\n", n_bytes, data); } void read_from_fifo(int fd, char** var) { int n_bytes; read(fd, &n_bytes, sizeof(int)); *var = (char *) malloc (n_bytes); printf("read '%s'\n", *var); read(fd, *var, n_bytes); } int main(int argc, char* argv[]) { pid_t pid = getpid(); //CRIA FIFO INFO_SRV_TO_CLIXXX char pid_string[PID_BUFFER_LEN]; sprintf(pid_string, "%d", pid); char* fifo_name_info_srv_to_cli; fifo_name_info_srv_to_cli = (char *) malloc ( (strlen(FIFO_DIR) + strlen(FIFO_NAME_INFO_SRV_TO_CLI) + strlen(pid_string) + 1 ) * sizeof(char) ); strcpy(fifo_name_info_srv_to_cli, FIFO_DIR); strcat(fifo_name_info_srv_to_cli, FIFO_NAME_INFO_SRV_TO_CLI); strcat(fifo_name_info_srv_to_cli, pid_string); int n = mkfifo(fifo_name_info_srv_to_cli, 0660); if (n < 0) { fprintf(stderr, "error creating %s\n", fifo_name_info_srv_to_cli); fprintf(stderr, "errno: %d\n", errno); exit(6); } int fd_cmd_cli_to_srv, fd_info_srv_to_cli; fd_cmd_cli_to_srv = open("/tmp/lrc_cmd_cli_to_srv", O_WRONLY); char command[COMMAND_MAX_LEN]; printf("> "); scanf("%s", command); while (strcmp(command, "/CONNECT")) { printf("O primeiro comando deverá ser \"/CONNECT\"\n"); printf("> "); scanf("%s", command); } //CRIA FIFO MSG_SRV_TO_CLIXXX char* fifo_name_msg_srv_to_cli; fifo_name_msg_srv_to_cli = (char *) malloc ( (strlen(FIFO_DIR) + strlen(FIFO_NAME_MSG_SRV_TO_CLI) + strlen(pid_string) + 1) * sizeof(char) ); strcpy(fifo_name_msg_srv_to_cli, FIFO_DIR); strcat(fifo_name_msg_srv_to_cli, FIFO_NAME_MSG_SRV_TO_CLI); strcat(fifo_name_msg_srv_to_cli, pid_string); n = mkfifo(fifo_name_msg_srv_to_cli, 0660); if (n < 0) { fprintf(stderr, "error creating %s\n", fifo_name_info_srv_to_cli); fprintf(stderr, "errno: %d\n", errno); exit(7); } // ENVIA COMANDO /CONNECT write_to_fifo(fd_cmd_cli_to_srv, pid_string); //envia pid do processo cliente write_to_fifo(fd_cmd_cli_to_srv, command); //envia commando /CONNECT write_to_fifo(fd_cmd_cli_to_srv, fifo_name_info_srv_to_cli); //envia nome de fifo INFO_SRV_TO_CLIXXX write_to_fifo(fd_cmd_cli_to_srv, fifo_name_msg_srv_to_cli); //envia nome de fifo MSG_TO_SRV_TO_CLIXXX // recebe do servidor a resposta ao comanddo /CONNECT printf("msg1\n"); printf("vamos tentar abrir %s\n", fifo_name_info_srv_to_cli); fd_info_srv_to_cli = open(fifo_name_info_srv_to_cli, O_RDONLY); printf("%s aberto", fifo_name_info_srv_to_cli); if (fd_info_srv_to_cli < 0) { fprintf(stderr, "erro ao criar %s\n", fifo_name_info_srv_to_cli); fprintf(stderr, "errno: %d\n", errno); } printf("msg2\n"); char* fifo_name_msg_cli_to_srv; printf("msg3\n"); read_from_fifo(fd_info_srv_to_cli, &fifo_name_msg_cli_to_srv); printf("msg4\n"); free(nickname); free(name); free(email); free(fifo_name_info_srv_to_cli); free(fifo_name_msg_srv_to_cli); unlink(fifo_name_msg_srv_to_cli); unlink(fifo_name_info_srv_to_cli); printf("fim\n"); return 0; } makefile: CC = gcc CFLAGS = -Wall -lpthread -fno-stack-protector all: client server client: client.c $(CC) $(CFLAGS) client.c -o client server: server.c $(CC) $(CFLAGS) server.c -o server clean: rm -f client server *~

    Read the article

  • openmp in mex : stackoverflow error

    - by Edwin
    i have got the following fraction of code that getting me the stack overflow error #pragma omp parallel shared(Mo1, Mo2, sum_normalized_p_gn, Data, Mean_Out,Covar_Out,Prior_Out, det) private(i) num_threads( number_threads ) { //every thread has a new copy double* normalized_p_gn = (double*)malloc(NMIX*sizeof(double)); #pragma omp critical { int id = omp_get_thread_num(); int threads = omp_get_num_threads(); mexEvalString("drawnow"); } #pragma omp for //some parallel process..... } the variables declared in the shared are created by malloc. and they consumes with large amount of memory there are 2 questions regarding to the above code. 1) why this would generate the stack overflow error( i.e. segmentation fault) before it goes into the parallel for loop? it works fine when it runs in the sequential mode.... 2) am i right to dynamic allocate memory for each thread like "normalized_p_gn" above? Regards Edwin

    Read the article

  • memcpy segmentation fault on linux but not os x

    - by Andre
    I'm working on implementing a log based file system for a file as a class project. I have a good amount of it working on my 64 bit OS X laptop, but when I try to run the code on the CS department's 32 bit linux machines, I get a seg fault. The API we're given allows writing DISK_SECTOR_SIZE (512) bytes at a time. Our log record consists of the 512 bytes the user wants to write as well as some metadata (which sector he wants to write to, the type of operation, etc). All in all, the size of the "record" object is 528 bytes, which means each log record spans 2 sectors on the disk. The first record writes 0-512 on sector 0, and 0-15 on sector 1. The second record writes 16-512 on sector 1, and 0-31 on sector 2. The third record writes 32-512 on sector 2, and 0-47 on sector 3. ETC. So what I do is read the two sectors I'll be modifying into 2 freshly allocated buffers, copy starting at record into buf1+the calculated offset for 512-offset bytes. This works correctly on both machines. However, the second memcpy fails. Specifically, "record+DISK_SECTOR_SIZE-offset" in the below code segfaults, but only on the linux machine. Running some random tests, it gets more curious. The linux machine reports sizeof(Record) to be 528. Therefore, if I tried to memcpy from record+500 into buf for 1 byte, it shouldn't have a problem. In fact, the biggest offset I can get from record is 254. That is, memcpy(buf1, record+254, 1) works, but memcpy(buf1, record+255, 1) segfaults. Does anyone know what I'm missing? Record *record = malloc(sizeof(Record)); record->tid = tid; record->opType = OP_WRITE; record->opArg = sector; int i; for (i = 0; i < DISK_SECTOR_SIZE; i++) { record->data[i] = buf[i]; // *buf is passed into this function } char* buf1 = malloc(DISK_SECTOR_SIZE); char* buf2 = malloc(DISK_SECTOR_SIZE); d_read(ad->disk, ad->curLogSector, buf1); d_read(ad->disk, ad->curLogSector+1, buf2); memcpy(buf1+offset, record, DISK_SECTOR_SIZE-offset); memcpy(buf2, record+DISK_SECTOR_SIZE-offset, offset+sizeof(Record)-sizeof(record->data));

    Read the article

  • SIGSEGV problem

    - by sickmate
    I'm designing a protocol (in C) to implement the layered OSI network structure, using cnet (http://www.csse.uwa.edu.au/cnet/). I'm getting a SIGSEGV error at runtime, however cnet compiles my source code files itself (I can't compile it through gcc) so I can't easily use any debugging tools such as gdb to find the error. Here's the structures used, and the code in question: typedef struct { char *data; } DATA; typedef struct { CnetAddr src_addr; CnetAddr dest_addr; PACKET_TYPE type; DATA data; } Packet; typedef struct { int length; int checksum; Packet datagram; } Frame; static void keyboard(CnetEvent ev, CnetTimerID timer, CnetData data) { char line[80]; int length; length = sizeof(line); CHECK(CNET_read_keyboard((void *)line, (unsigned int *)&length)); // Reads input from keyboard if(length > 1) { /* not just a blank line */ printf("\tsending %d bytes - \"%s\"\n", length, line); application_downto_transport(1, line, &length); } } void application_downto_transport(int link, char *msg, int *length) { transport_downto_network(link, msg, length); } void transport_downto_network(int link, char *msg, int *length) { Packet *p; DATA *d; p = (Packet *)malloc(sizeof(Packet)); d = (DATA *)malloc(sizeof(DATA)); d->data = msg; p->data = *d; network_downto_datalink(link, (void *)p, length); } void network_downto_datalink(int link, Packet *p, int *length) { Frame *f; // Encapsulate datagram and checksum into a Frame. f = (Frame *)malloc(sizeof(Frame)); f->checksum = CNET_crc32((unsigned char *)(p->data).data, *length); // Generate 32-bit CRC for the data. f->datagram = *p; f->length = sizeof(f); //Pass Frame to the CNET physical layer to send Frame to the require link. CHECK(CNET_write_physical(link, (void *)f, (size_t *)f->length)); free(p->data); free(p); free(f); } I managed to find that the line: CHECK(CNET_write_physical(link, (void *)f, (size_t *)f-length)); is causing the segfault but I can't work out why. Any help is greatly appreciated.

    Read the article

  • Dereferencing pointers without pointing them at a variable

    - by Miguel
    I'm having trouble understanding how some pointers work. I always thought that when you created a pointer variable (p), you couldn't deference and assign (*p = value) unless you either malloc'd space for it (p = malloc(x)), or set it to the address of another variable (p = &a) However in this code, the first assignment works consistently, while the last one causes a segfault: typedef struct { int value; } test_struct; int main(void) { //This works int* colin; *colin = 5; //This never works test_struct* carter; carter->value = 5; } Why does the first one work when colin isn't pointing at any spare memory? And why does the 2nd never work? I'm writing this in C, but people with C++ knowledge should be able to answer this as well.

    Read the article

  • a program similar to ls with some modifications

    - by Bond
    Hi, here is a simple puzzle I wanted to discuss. A C program to take directory name as command line argument and print last 3 directories and 3 files in all subdirectories without using api 'system' inside it. suppose directory bond0 contains bond1, di2, bond3, bond4, bond5 and my_file1, my_file2, my_file3, my_file4, my_file5, my_file6 and bond1 contains bond6 my_file7 my_file8 my_file9 my_file10 program should output - bond3, bond4, bond5, my_file4, my_file5, my_file6, bond6, my_file8, my_file9, my_file10 My code for the above problem is here #include<dirent.h> #include<unistd.h> #include<string.h> #include<sys/stat.h> #include<stdlib.h> #include<stdio.h> char *directs[20], *files[20]; int i = 0; int j = 0; int count = 0; void printdir(char *); int count_dirs(char *); int count_files(char *); int main() { char startdir[20]; printf("Scanning user directories\n"); scanf("%s", startdir); printdir(startdir); } void printdir(char *dir) { printf("printdir called %d directory is %s\n", ++count, dir); DIR *dp = opendir(dir); int nDirs, nFiles, nD, nF; nDirs = 0; nFiles = 0; nD = 0; nF = 0; if (dp) { struct dirent *entry = 0; struct stat statBuf; nDirs = count_dirs(dir); nFiles = count_files(dir); printf("The no of subdirectories in %s is %d \n", dir, nDirs); printf("The no of files in %s is %d \n", dir, nFiles); while ((entry = readdir(dp)) != 0) { if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } char *filepath = malloc(strlen(dir) + strlen(entry->d_name) + 2); if (filepath) { sprintf(filepath, "%s/%s", dir, entry->d_name); if (lstat(filepath, &statBuf) != 0) { } if (S_ISDIR(statBuf.st_mode)) { nD++; if ((nDirs - nD) < 3) { printf("The directory is %s\n",entry->d_name); } } else { nF++; if ((nFiles - nF) < 3) { printf("The files are %s\n", entry->d_name); } //if } //else free(filepath); } //if(filepath) } //while while ((entry = readdir(dp)) != 0) { if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } printf("In second while loop *entry=%s\n",entry->d_name); char *filepath = malloc(strlen(dir) + strlen(entry->d_name) + 2); if (filepath) { sprintf(filepath, "%s/%s", dir, entry->d_name); if (lstat(filepath, &statBuf) != 0) { } if (S_ISDIR(statBuf.st_mode)) { printdir(entry->d_name); } } //else free(filepath); } //2nd while closedir(dp); } else { fprintf(stderr, "Error, cannot open directory %s\n", dir); } } //printdir int count_dirs(char *dir) { DIR *dp = opendir(dir); int nD; nD = 0; if (dp) { struct dirent *entry = 0; struct stat statBuf; while ((entry = readdir(dp)) != 0) { if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } char *filepath = malloc(strlen(dir) + strlen(entry->d_name) + 2); if (filepath) { sprintf(filepath, "%s/%s", dir, entry->d_name); if (lstat(filepath, &statBuf) != 0) { fprintf(stderr, "File Not found? %s\n", filepath); } if (S_ISDIR(statBuf.st_mode)) { nD++; } else { continue; } free(filepath); } } closedir(dp); } else { fprintf(stderr, "Error, cannot open directory %s\n", dir); } return nD; } int count_files(char *dir) { DIR *dp = opendir(dir); int nF; nF = 0; if (dp) { struct dirent *entry = 0; struct stat statBuf; while ((entry = readdir(dp)) != 0) { if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } char *filepath = malloc(strlen(dir) + strlen(entry->d_name) + 2); if (filepath) { sprintf(filepath, "%s/%s", dir, entry->d_name); if (lstat(filepath, &statBuf) != 0) { fprintf(stderr, "File Not found? %s\n", filepath); } if (S_ISDIR(statBuf.st_mode)) { continue; } else { nF++; } free(filepath); } } closedir(dp); } else { fprintf(stderr, "Error, cannot open file %s\n", dir); } return nF; } The above code I wrote is a bit not functioning correctly can some one help me to understand the error which is coming.So that I improve it further.There seems to be some small glitch which is not clear to me right now.

    Read the article

  • Using objects with STL vector - minimal set of methods

    - by osgx
    Hello What is "minimal framework" (necessary methods) of object, which I will use with STL <vector>? For my assumptions: #include <vector> #include <cstring> using namespace std; class Doit { private: char *a; public: Doit(){a=(char*)malloc(10);} ~Doit(){free(a);} }; int main(){ vector<Doit> v(10); } gives *** glibc detected *** ./a.out: double free or corruption (fasttop): 0x0804b008 *** Aborted and in valgrind: malloc/free: 2 allocs, 12 frees, 50 bytes allocated.

    Read the article

  • EXC_BAD_ACCESS at UITableView on IOS

    - by Suprie
    Hi all, When scrolling through table, my application crash and console said it was EXC_BAD_ACCESS. I've look everywhere, and people suggest me to use NSZombieEnabled on my executables environment variables. I've set NSZombieEnabled, NSDebugEnabled, MallocStackLogging and MallocStackLoggingNoCompact to YES on my executables. But apparently i still can't figure out which part of my program that cause EXC_BAD_ACCESS. This is what my console said [Session started at 2010-12-21 21:11:21 +0700.] GNU gdb 6.3.50-20050815 (Apple version gdb-1510) (Wed Sep 22 02:45:02 UTC 2010) Copyright 2004 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. Type "show copying" to see the conditions. There is absolutely no warranty for GDB. Type "show warranty" for details. This GDB was configured as "x86_64-apple-darwin".sharedlibrary apply-load-rules all Attaching to process 9335. TwitterSearch(9335) malloc: recording malloc stacks to disk using standard recorder TwitterSearch(9335) malloc: process 9300 no longer exists, stack logs deleted from /tmp/stack-logs.9300.TwitterSearch.suirlR.index TwitterSearch(9335) malloc: stack logs being written into /tmp/stack- logs.9335.TwitterSearch.tQJAXk.index 2010-12-21 21:11:25.446 TwitterSearch[9335:207] View Did Load Program received signal: “EXC_BAD_ACCESS”. And this is when i tried to type backtrace on gdb : Program received signal: “EXC_BAD_ACCESS”. (gdb) backtrace #0 0x00f20a67 in objc_msgSend () #1 0x0565cd80 in ?? () #2 0x0033b7fa in -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:withIndexPath:] () #3 0x0033177f in -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:] () #4 0x00346450 in -[UITableView(_UITableViewPrivate) _updateVisibleCellsNow:] () #5 0x0033e538 in -[UITableView layoutSubviews] () #6 0x01ffc451 in -[CALayer layoutSublayers] () #7 0x01ffc17c in CALayerLayoutIfNeeded () #8 0x01ff537c in CA::Context::commit_transaction () #9 0x01ff50d0 in CA::Transaction::commit () #10 0x020257d5 in CA::Transaction::observer_callback () #11 0x00d9ffbb in __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ () #12 0x00d350e7 in __CFRunLoopDoObservers () #13 0x00cfdbd7 in __CFRunLoopRun () #14 0x00cfd240 in CFRunLoopRunSpecific () #15 0x00cfd161 in CFRunLoopRunInMode () #16 0x01a73268 in GSEventRunModal () #17 0x01a7332d in GSEventRun () #18 0x002d642e in UIApplicationMain () #19 0x00001d4e in main (argc=1, argv=0xbfffee34) at /Users/suprie/Documents/Projects/Self/cocoa/TwitterSearch/main.m:14 I really appreciate for any clue to help me debug my application. EDIT this is the Header file of table #import <UIKit/UIKit.h> @interface TwitterTableViewController : UITableViewController { NSMutableArray *twitters; } @property(nonatomic,retain) NSMutableArray *twitters; @end and the implementation file #import "TwitterTableViewController.h" @implementation TwitterTableViewController @synthesize twitters; #pragma mark - #pragma mark Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number of sections. return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // Return the number of rows in the section. return [twitters count]; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 90.0f; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { const NSInteger TAG_IMAGE_VIEW = 1001; const NSInteger TAG_TWEET_VIEW = 1002; const NSInteger TAG_FROM_VIEW = 1003; static NSString *CellIdentifier = @"Cell"; UIImageView *imageView; UILabel *tweet; UILabel *from; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; // Image imageView = [[[[UIImageView alloc] initWithFrame:CGRectMake(5.0f, 5.0f, 60.0f, 60.0f)] autorelease] retain]; [cell.contentView addSubview:imageView]; imageView.tag = TAG_IMAGE_VIEW; // Tweet tweet = [[[UILabel alloc] initWithFrame:CGRectMake(105.0f, 5.0f, 200.0f, 50.0f)] autorelease]; [cell.contentView addSubview:tweet]; tweet.tag = TAG_TWEET_VIEW; tweet.numberOfLines = 2; tweet.font = [UIFont fontWithName:@"Helvetica" size:12]; tweet.textColor = [UIColor blackColor]; tweet.backgroundColor = [UIColor clearColor]; // From from = [[[UILabel alloc] initWithFrame:CGRectMake(105.0f, 55.0, 200.0f, 35.0f)] autorelease]; [cell.contentView addSubview:from]; from.tag = TAG_FROM_VIEW; from.numberOfLines = 1; from.font = [UIFont fontWithName:@"Helvetica" size:10]; from.textColor = [UIColor blackColor]; from.backgroundColor = [UIColor clearColor]; } // Configure the cell... NSMutableDictionary *twitter = [twitters objectAtIndex:(NSInteger) indexPath.row]; // cell.text = [twitter objectForKey:@"text"]; tweet.text = (NSString *) [twitter objectForKey:@"text"]; tweet.hidden = NO; from.text = (NSString *) [twitter objectForKey:@"from_user"]; from.hidden = NO; NSString *avatar_url = (NSString *)[twitter objectForKey:@"profile_image_url"]; NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: avatar_url]]; imageView.image = [UIImage imageWithData: imageData]; imageView.hidden = NO; return cell; } #pragma mark - #pragma mark Table view delegate - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSMutableDictionary *twitter = [twitters objectAtIndex:(NSInteger)indexPath.row]; NSLog(@"Twit ini kepilih :%@", [twitter objectForKey:@"text"]); } #pragma mark - #pragma mark Memory management - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; } - (void)viewDidUnload { } - (void)dealloc { [super dealloc]; } @end

    Read the article

  • Array subscript is not an integer

    - by Dimitri
    Hello folks, following this previous question Malloc Memory Corruption in C, now i have another problem. I have the same code. Now I am trying to multiply the values contained in the arrays A * vc and store in res. Then A is set to zero and i do a second multiplication with res and vc and i store the values in A. (A and Q are square matrices and mc and vc are N lines two columns matrices or arrays). Here is my code : int jacobi_gpu(double A[], double Q[], double tol, long int dim){ int nrot, p, q, k, tid; double c, s; double *mc, *vc, *res; int i,kc; double vc1, vc2; mc = (double *)malloc(2 * dim * sizeof(double)); vc = (double *)malloc(2 * dim * sizeof(double)); vc = (double *)malloc(dim * dim * sizeof(double)); if( mc == NULL || vc == NULL){ fprintf(stderr, "pb allocation matricre\n"); exit(1); } nrot = 0; for(k = 0; k < dim - 1; k++){ eye(mc, dim); eye(vc, dim); for(tid = 0; tid < floor(dim /2); tid++){ p = (tid + k)%(dim - 1); if(tid != 0) q = (dim - tid + k - 1)%(dim - 1); else q = dim - 1; printf("p = %d | q = %d\n", p, q); if(fabs(A[p + q*dim]) > tol){ nrot++; symschur2(A, dim, p, q, &c, &s); mc[2*tid] = p; vc[2 * tid] = c; mc[2*tid + 1] = q; vc[2*tid + 1] = -s; mc[2*tid + 2*(dim - 2*tid) - 2] = p; vc[2*tid + 2*(dim - 2*tid) - 2 ] = s; mc[2*tid + 2*(dim - 2*tid) - 1] = q; vc[2 * tid + 2*(dim - 2*tid) - 1 ] = c; } } for( i = 0; i< dim; i++){ for(kc=0; kc < dim; kc++){ if( kc < floor(dim/2)) { vc1 = vc[2*kc + i*dim]; vc2 = vc[2*kc + 2*(dim - 2*kc) - 2]; }else { vc1 = vc[2*kc+1 + i*dim]; vc2 = vc[2*kc - 2*(dim - 2*kc) - 1]; } res[kc + i*dim] = A[mc[2*kc] + i*dim]*vc1 + A[mc[2*kc + 1] + i*dim]*vc2; } } zero(A, dim); for( i = 0; i< dim; i++){ for(kc=0; kc < dim; k++){ if( k < floor(dim/2)){ vc1 = vc[2*kc + i*dim]; vc2 = vc[2*kc + 2*(dim - 2*kc) - 2]; }else { vc1 = vc[2*kc+1 + i*dim]; vc2 = vc[2*kc - 2*(dim - 2*kc) - 1]; } A[kc + i*dim] = res[mc[2*kc] + i*dim]*vc1 + res[mc[2*kc + 1] + i*dim]*vc2; } } affiche(mc,dim,2,"Matrice creuse"); affiche(vc,dim,2,"Valeur creuse"); } free(mc); free(vc); free(res); return nrot; } When i try to compile, i have this error : jacobi_gpu.c: In function ‘jacobi_gpu’: jacobi_gpu.c:103: error: array subscript is not an integer jacobi_gpu.c:103: error: array subscript is not an integer jacobi_gpu.c:118: error: array subscript is not an integer jacobi_gpu.c:118: error: array subscript is not an integer make: *** [jacobi_gpu.o] Erreur 1 The corresponding lines are where I store the results in res and A : res[kc + i*dim] = A[mc[2*kc] + i*dim]*vc1 + A[mc[2*kc + 1] + i*dim]*vc2; and A[kc + i*dim] = res[mc[2*kc] + i*dim]*vc1 + res[mc[2*kc + 1] + i*dim]*vc2; Can someone explain me what is this error and how can i correct it? Thanks for your help. ;)

    Read the article

  • Differences between matrix implementation in C

    - by tempy
    I created two 2D arrays (matrix) in C in two different ways. I don't understand the difference between the way they're represented in the memory, and the reason why I can't refer to them in the same way: scanf("%d", &intMatrix1[i][j]); //can't refer as &intMatrix1[(i * lines)+j]) scanf("%d", &intMatrix2[(i * lines)+j]); //can't refer as &intMatrix2[i][j]) What is the difference between the ways these two arrays are implemented and why do I have to refer to them differently? How do I refer to an element in each of the arrays in the same way (?????? in my printMatrix function)? int main() { int **intMatrix1; int *intMatrix2; int i, j, lines, columns; lines = 3; columns = 2; /************************* intMatrix1 ****************************/ intMatrix1 = (int **)malloc(lines * sizeof(int *)); for (i = 0; i < lines; ++i) intMatrix1[i] = (int *)malloc(columns * sizeof(int)); for (i = 0; i < lines; ++i) { for (j = 0; j < columns; ++j) { printf("Type a number for intMatrix1[%d][%d]\t", i, j); scanf("%d", &intMatrix1[i][j]); } } /************************* intMatrix2 ****************************/ intMatrix2 = (int *)malloc(lines * columns * sizeof(int)); for (i = 0; i < lines; ++i) { for (j = 0; j < columns; ++j) { printf("Type a number for intMatrix2[%d][%d]\t", i, j); scanf("%d", &intMatrix2[(i * lines)+j]); } } /************** printing intMatrix1 & intMatrix2 ****************/ printf("intMatrix1:\n\n"); printMatrix(*intMatrix1, lines, columns); printf("intMatrix2:\n\n"); printMatrix(intMatrix2, lines, columns); } /************************* printMatrix ****************************/ void printMatrix(int *ptArray, int h, int w) { int i, j; printf("Printing matrix...\n\n\n"); for (i = 0; i < h; ++i) for (j = 0; j < w; ++j) printf("array[%d][%d] ==============> %d\n, i, j, ??????); }

    Read the article

  • Double indirection and structures passed into a function

    - by ZPS
    I am curious why this code works: typedef struct test_struct { int id; } test_struct; void test_func(test_struct ** my_struct) { test_struct my_test_struct; my_test_struct.id=267; *my_struct = &my_test_struct; } int main () { test_struct * main_struct; test_func(&main_struct); printf("%d\n",main_struct->id); } This works, but pointing to the memory address of a functions local variable is a big no-no, right? But if i used a structure pointer and malloc, that would be the correct way, right? void test_func(test_struct ** my_struct) { test_struct *my_test_struct; my_test_struct = malloc(sizeof(test_struct)); my_test_struct->id=267; *my_struct = my_test_struct; } int main () { test_struct * main_struct; test_func(&main_struct); printf("%d\n",main_struct->id); }

    Read the article

  • I'd like to know why a function executes fine when called from x but not when called from y

    - by Roland
    When called from archive(), readcont(char *filename) executes fine! Called from runoptions() though, it fails to list the files "archived"! why is this? The program must run in terminal. Use -h as a parameter to view the usage. This program is written to "archive" text files into ".rldzip" files. readcont( char *x) should show the files archived in file (*x) a) Successful call Use the program to archive 3 text files: rldzip.exe a.txt b.txt c.txt FILEXY -a archive() will call readcont and it will work showing the files archived after the binary FILEXY will be created. b) Unsuccessful call After the file is created, use: rldzip.exe FILEXY.rldzip -v You can see that the function crashes! I'd like to know why is this happening! /* Sa se scrie un program care: a) arhiveaza fisiere b) dezarhiveaza fisierele athivate */ #include<stdio.h> #include<stdlib.h> #include<conio.h> #include<string.h> struct content{ char *text; char *flname; }*arc; FILE *f; void readcont(char *x){ FILE *p; if((p = fopen(x, "rb")) == NULL){ perror("Critical error: "); exit(EXIT_FAILURE); } content aux; int i; fread(&i, sizeof(int), 1, p); printf("\nFiles in %s \n\n", x); while(i-- >1 && fread(&aux, sizeof(struct content), 1, p) != 0) printf("%s \n", aux.flname); fclose(p); printf("\n\n"); } void archive(int argc, char **argv){ int i; char inttext[5000], textline[1000]; //Allocate dynamic memory for the content to be archived! arc = (content*)malloc(argc * sizeof(content)); for(i=1; i< argc; i++) { if((f = fopen(argv[i], "r")) == NULL){ printf("%s: ", argv[i]); perror(""); exit(EXIT_FAILURE); } while(!feof(f)){ fgets(textline, 5000, f); strcat(inttext, textline); } arc[i-1].text = (char*)malloc(strlen(inttext) + 1); strcpy(arc[i-1].text, inttext); arc[i-1].flname = (char*)malloc(strlen(argv[i]) + 1); strcpy(arc[i-1].flname, argv[i]); fclose(f); } char *filen; filen=(char*)malloc(strlen(argv[argc])+1+7); strcpy(filen, argv[argc]); strcat(filen, ".rldzip"); f = fopen(filen, "wb"); fwrite(&argc, sizeof(int), 1, f); fwrite(arc, sizeof(content), argc, f); fclose(f); printf("Success! "); for(i=1; i< argc; i++) { (i==argc-1)? printf("and %s ", argv[i]) : printf("%s ", argv[i]); } printf("compressed into %s", filen); readcont(filen); free(filen); } void help(char *v){ printf("\n\n----------------------RLDZIP----------------------\n\nUsage: \n\n Archive n files: \n\n%s $file[1] $file[2] ... $file[n] $output -a\n\nExample:\n%s a.txt b.txt c.txt output -a\n\n\n\nView files:\n\n %s $file.rldzip -v\n\nExample:\n %s fileE.rldzip -v\n\n", v, v, v, v); } void runoptions(int c, char **v){ int i; if(c < 2){ printf("Arguments missing! Use -h for help"); } else{ for(i=0; i<c; i++) if(strcmp(v[i], "-h") == 0){ help(v[0]); exit(2); } for(i=0; i<c; i++) if(strcmp(v[i], "-v") == 0){ if(c != 3){ printf("Arguments misused! Use -h for help"); exit(2); } else { printf("-%s-", v[1]); readcont(v[1]); } } } if(strcmp(v[c-1], "-a") == 0) archive(c-2, v); } main(int argc, char **argv) { runoptions(argc, argv); }

    Read the article

  • On Memory Allocation and C++

    - by Arpan
    And I quote from MSDN http://msdn.microsoft.com/en-us/library/aa366533(VS.85).aspx: The malloc function has the disadvantage of being run-time dependent. The new operator has the disadvantage of being compiler dependent and language dependent. Now the questions folks: a) What do we mean that malloc is run-time dependent? What kind of dynamic memory allocation functions can be independent of run-time? This statement sounds real strange. b) new is language dependent? Of course it should be right? Are HeapAlloc, LocalAlloc etc language independent? c) From a pure performance perspective are the MSVC provided routines preferable? Arpan

    Read the article

  • Initializing and accessing a pointer from an array of pointers

    - by idealistikz
    Suppose I have the following: void **Init(int numElems) { //What is the best way to intialize 'ptrElems' to store an array of void *'s? void **ptrElems = malloc(numElems * sizeof(void *)); return ptrElems; } //What is the best way to return a pointer pointing at the index passed as a parameter? void **GetPtr(void **ptrElems, int index) { void **elem = elems + (index * sizeof(void *)); return elem; } First, what is the best way to intialize 'ptrElems' to store an array of pointers? I use malloc because assigning it to an array will not persist after the end of the function. Second, what is the best way to point to the pointer at the specified index? I tried typecasting the first line of the 'GetPtr' function to ensure proper pointer arithmetic, but I receive the warning, 'initialization from incompatible pointer type'. Is it necessary to typecast?

    Read the article

  • please help me to find Bug in my Code (segmentation fault)

    - by Vikramaditya Battina
    i am tring to solve this http://www.spoj.com/problems/LEXISORT/ question it working fine in visual studio compiler and IDEone also but when i running in SPOJ compiler it is getting SEGSIGV error Here my code goes #include<stdio.h> #include<stdlib.h> #include<string.h> char *getString(); void lexisort(char **str,int num); void countsort(char **str,int i,int num); int main() { int num_test; int num_strings; char **str; int i,j; scanf("%d",&num_test); for(i=0;i<num_test;i++) { scanf("%d",&num_strings); str=(char **)malloc(sizeof(char *)*num_strings); for(j=0;j<num_strings;j++) { str[j]=(char *)malloc(sizeof(char)*11); scanf("%s",str[j]); } lexisort(str,num_strings); for(j=0;j<num_strings;j++) { printf("%s\n",str[j]); free(str[j]); } free(str); } return 0; } void lexisort(char **str,int num) { int i; for(i=9;i>=0;i--) { countsort(str,i,num); } } void countsort(char **str,int i,int num) { int buff[52]={0,0},k,x; char **temp=(char **)malloc(sizeof(char *)*num); for(k=0;k<52;k++) { buff[k]=0; } for(k=0;k<num;k++) { if(str[k][i]>='A' && str[k][i]<='Z') { buff[(str[k][i]-'A')]++; } else { buff[26+(str[k][i]-'a')]++; } } for(k=1;k<52;k++) { buff[k]=buff[k]+buff[k-1]; } for(k=num-1;k>=0;k--) { if(str[k][i]>='A' && str[k][i]<='Z') { x=buff[(str[k][i]-'A')]; temp[x-1]=str[k]; buff[(str[k][i]-'A')]--; } else { x=buff[26+(str[k][i]-'a')]; temp[x-1]=str[k]; buff[26+(str[k][i]-'a')]--; } } for(k=0;k<num;k++) { str[k]=temp[k]; } free(temp); }

    Read the article

  • assignment makes pointer from integer without a cast

    - by mrblippy
    hi, i am trying to make a linked list and create some methods. but i am getting the error assignment makes pointer from integer without a cast. #include <stdio.h> #include <stdlib.h> #include "students.h" node_ptr create(void) { node_ptr students = (node_ptr) malloc(sizeof(struct node)); students->ID = 0; students->name = NULL; students->next = NULL; return students; } void insert_in_order(int n, node_ptr list) { node_ptr before = list; node_ptr new_node = (node_ptr) malloc(sizeof(struct node)); new_node->ID = n;//error is here i think while(before->next && (before->next->ID < n)) { before = before->next; } new_node->next = before->next; before->next = new_node; }

    Read the article

  • c: memory allocation (what's going on)

    - by facha
    Hi, everyone Please take a look at this piece of code. I'm allocating one byte for the first variable and another byte for the second one. However, it seems like the compiler allocates more (or I'm missing something). The program outputs both strings, even though their length is more the one byte. void main() { char* some1 = malloc(1); sprintf(some1,"cool"); char* some2 = malloc(1); sprintf(some2,"face"); printf("%s ",some1); printf("%s\n",some2); } Please, could anyone spot some light on what's going on when memory is being allocated.

    Read the article

  • Storing objects in STL vector - minimal set of methods

    - by osgx
    Hello What is "minimal framework" (necessary methods) of object, which I will store in STL <vector>? For my assumptions: #include <vector> #include <cstring> using namespace std; class Doit { private: char *a; public: Doit(){a=(char*)malloc(10);} ~Doit(){free(a);} }; int main(){ vector<Doit> v(10); } gives *** glibc detected *** ./a.out: double free or corruption (fasttop): 0x0804b008 *** Aborted and in valgrind: malloc/free: 2 allocs, 12 frees, 50 bytes allocated.

    Read the article

  • I serialized a C++ object, how to allocate memory for it without knowing what type it is?

    - by Neo_b
    Hello, I have serialized a C++ object and I wish to allocate space for it, although I can't use the "new" operator, because I do not know the object's class. I tried using malloc(sizeof(object)), although trying to typecast the pointer to the type the serialized object is of, the program shut down. Where is the information about the object class stored? class object { public: virtual void somefunc(); int someint; }; class objectchild:public object { } object *o=(object*)malloc(sizeof(objectchild)); cout << int(dynamic_cast<objectchild*>(o)) << endl; This causes a program shutdown. Thank you in advance.

    Read the article

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