Search Results

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

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

  • Read and write struct in C

    - by Sergey
    I have a struct: typedef struct student { char fname[30]; char sname[30]; char tname[30]; Faculty fac; int course; char group[10]; int room; int bad; } Student; I read it from the file: Database * dbOpen(char *fname) { FILE *fp = fopen(fname, "rb"); List *lst, *temp; Student *std; Database *db = malloc(sizeof(*db)); if (!fp) return NULL; FileNameS = fname; std = malloc(sizeof(*std)); if (!fread(std, sizeof(*std), 1, fp)) { db->head = db->tail = NULL; return db; } lst = malloc(sizeof(*lst)); lst->s = std; lst->prev = NULL; db->head = lst; while (!feof(fp)) { fread(std, sizeof(*std), 1, fp); temp = malloc(sizeof(*temp)); temp->s = std; temp->prev = lst; lst->next = temp; lst = temp; } lst->next = NULL; db->tail = lst; fclose(fp); return db; } And I have a problem... At the last record i have a such file pointer: `fp 0x10311448 {_ptr=0x00344b90 "???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? _ _iobuf * ` And i read last record 2 times... Save file code: void * dbClose(Database *db) { FILE *fp = fopen(FileNameS, "w+b"); List *lst, *temp; lst = db->head; while(lst != NULL) { fwrite(lst->s, sizeof(*(lst->s)), 1, fp); temp = lst; lst = lst->next; free(temp); } free(db); fclose(fp); }

    Read the article

  • Assignment operator that calls a constructor is broken

    - by Delan Azabani
    I've implemented some of the changes suggested in this question, and (thanks very much) it works quite well, however... in the process I've seemed to break the post-declaration assignment operator. With the following code: #include <cstdio> #include "ucpp" main() { ustring a = "test"; ustring b = "ing"; ustring c = "- -"; ustring d = "cafe\xcc\x81"; printf("%s\n", (a + b + c[1] + d).encode()); } I get a nice "testing cafe´" message. However, if I modify the code slightly so that the const char * conversion is done separately, post-declaration: #include <cstdio> #include "ucpp" main() { ustring a = "test"; ustring b = "ing"; ustring c = "- -"; ustring d; d = "cafe\xcc\x81"; printf("%s\n", (a + b + c[1] + d).encode()); } the ustring named d becomes blank, and all that is output is "testing ". My new code has three constructors, one void (which is probably the one being incorrectly used, and is used in the operator+ function), one that takes a const ustring &, and one that takes a const char *. The following is my new library code: #include <cstdlib> #include <cstring> class ustring { int * values; long len; public: long length() { return len; } ustring() { len = 0; values = (int *) malloc(0); } ustring(const ustring &input) { len = input.len; values = (int *) malloc(sizeof(int) * len); for (long i = 0; i < len; i++) values[i] = input.values[i]; } ustring operator=(ustring input) { ustring result(input); return result; } ustring(const char * 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; input[i]; 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; } len = s; } ustring operator=(const char * input) { ustring result(input); return result; } 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

  • How can I get a file's size in C?

    - by Nino
    How can I find out the size of a file? I opened with an application written in C. I would like to know the size, because I want to put the content of the loaded file into a string, which I alloc using malloc(). Just writing malloc(10000*sizeof(char)); is IMHO a bad idea.

    Read the article

  • Unable to free const pointers in C

    - by lego69
    How can I free a const char*? I allocated new memory using malloc, and when I'm trying to free it I always receive the error "incompatible pointer type" The code that causes this is something like: char* name="Arnold"; const char* str=(const char*)malloc(strlen(name)+1); free(str); // error here

    Read the article

  • why gcc emits segmentation ,after my code run

    - by gcc
    every time ,why have I encountered with segmentation fault ? still,I have not found my fault sometimes, gcc emits segmentation fault ,sometimes, memory satck limit is exceeded I think you will understand (easily) what is for that code void my_main() { char *tutar[50],tempc; int i=0,temp,g=0,a=0,j=0,d=1,current=0,command=0,command2=0; do{ tutar[i]=malloc(sizeof(int)); scanf("%s",tutar[i]); temp=*tutar[i]; } while(temp=='x'); i=0; num_arrays=atoi(tutar[i]); i=1; tempc=*tutar[i]; if(tempc!='x' && tempc!='d' && tempc!='a' && tempc!='j') { current=1; arrays[current]=malloc(sizeof(int)); l_arrays[current]=calloc(1,sizeof(int)); c_arrays[current]=calloc(1,sizeof(int));} i=1; current=1; while(1) { tempc=*tutar[i]; if(tempc=='x') break; if(tempc=='n') { ++current; arrays[current]=malloc(sizeof(int)); l_arrays[current]=calloc(1,sizeof(int)); c_arrays[current]=calloc(1,sizeof(int)); ++i; continue; } if(tempc=='d') { ++i; command=atoi(tutar[i])-1; free(arrays[command]); free(l_arrays[command]); free(c_arrays[command]); ++i; continue; } if(tempc=='j') { ++i; current=atoi(tutar[i])-1; if(arrays[current]==NULL) { arrays[current]=malloc(sizeof(int)); l_arrays[current]=calloc(1,sizeof(int)); c_arrays[current]=calloc(1,sizeof(int)); ++i; } else { a=l_arrays[current]; j=l_arrays[current]; ++i;} continue; } } }

    Read the article

  • C segmentation fault before/during return statement

    - by wolfPack88
    I print the value that I'm returning right before my return statement, and tell my code to print the value that was returned right after the function call. However, I get a segmentation fault after my first print statement and before my second (also interesting to note, this always happens on the third time the function is called; never the first or the second, never fourth or later). I tried printing out all of the data that I'm working on to see if the rest of my code was doing something it maybe shouldn't, but my data up to that point looks fine. Here's the function: int findHydrogen(struct Amino* amino, int nPos, float* diff, int totRead) { struct Atom* atoms; int* bonds; int numBonds; int i; int retVal; int numAtoms; numAtoms = (*amino).numAtoms; atoms = (struct Atom *) malloc(sizeof(struct Atom) * numAtoms); atoms = (*amino).atoms; numBonds = atoms[nPos].numBonds; bonds = (int *) malloc(sizeof(int) * numBonds); bonds = atoms[nPos].bonds; for(i = 0; i < (*amino).numAtoms; i++) printf("ATOM\t\t%d %s\t0001\t%f\t%f\t%f\n", i + 1, atoms[i].type, atoms[i].x, atoms[i].y, atoms[i].z); for(i = 0; i < numBonds; i++) if(atoms[bonds[i] - totRead].type[0] == 'H') { diff[0] = atoms[bonds[i] - totRead].x - atoms[nPos].x; diff[1] = atoms[bonds[i] - totRead].y - atoms[nPos].y; diff[2] = atoms[bonds[i] - totRead].z - atoms[nPos].z; retVal = bonds[i] - totRead; bonds = (int *) malloc(sizeof(int)); free(bonds); atoms = (struct Atom *) malloc(sizeof(struct Atom)); free(atoms); printf("2 %d\n", retVal); return retVal; } } As I mentioned before, it works fine the first two times I run it, the third time it prints the correct value of retVal, then seg faults somewhere before it gets to where I called the function, which I do as: hPos = findHydrogen((&aminoAcid[i]), nPos, diff, totRead); printf("%d\n", hPos);

    Read the article

  • problems with 'free' in C

    - by lego69
    hello, can somebody please explain can I free const char* ? I allocated new memory using malloc and when I'm trying to free it I always receive an error incompatible pointer type thanks in advance something like this char* name="Arnold"; const char* str=malloc(stlen(name)+1); free(str); <- here bug

    Read the article

  • C: copying some structs causes strange behavior

    - by Jenny B
    I have an annoying bug in the line rq->tickets[rq->usedContracts] = toAdd; if i do: rq->tickets[0] = toAdd the program crashes if i do rq->tickets[1] = toAdd; it works valgrind says ==19501== Use of uninitialised value of size 8 and ==19501== Invalid write of size 8 for this very line. What is wrong? struct TS_element { int travels; int originalTravels; int cost; char** dates; int moneyLeft; } TicketSet; struct RQ_element { int usedContracts; struct TS_element* tickets; } RabQav; TicketSetStatus tsCreate(TicketSet* t, int n, int c) { if (n <= 0) return TS_ILLEGAL_PARAMETER; TicketSet* myTicketSet = (TicketSet*) malloc(sizeof(TicketSet)); if (myTicketSet == NULL) { return TS_CANNOT_CREATE; } myTicketSet->usedTravels = 0; myTicketSet->originalTravels = n; myTicketSet->cost = c; myTicketSet->moneyLeft = n * c; char** dates = malloc(sizeof(char**)* (n)); //todo maybe c99 allows dynamic arrays? for (int i = 0; i < n; i++) { dates[i] = malloc(sizeof(char)*GOOD_LENGTH+1); if (dates[i] == NULL) { free(dates); free(t); return TS_CANNOT_CREATE; } } myTicketSet->dates = dates; *t = *myTicketSet; return TS_SUCCESS; } static void copyTicketSets(TicketSet* dest, const TicketSet* source) { dest->usedTravels = source->usedTravels; dest->originalTravels = source->originalTravels; dest->cost = source->cost; dest->moneyLeft = source->moneyLeft; for (int i = 0; i < source->originalTravels; i++) { if (NULL != source->dates[i]) { free(dest->dates[i]); dest->dates[i] = malloc(sizeof(char) * GOOD_LENGTH + 1); if (dest->dates[i] == NULL) { free(dest->dates); //todo free dates 0...i-1 free(dest); return; } strcpy(dest->dates[i], source->dates[i]); } } } RabQavStatus rqLoadTS(RabQav* rq, TicketSet t, DateTime dt) { TicketSet toAdd; TicketSetStatus res = tsCreate(&toAdd, t.originalTravels, t.cost); if (res != TS_SUCCESS) { return RQ_FAIL; } copyTicketSets(&toAdd, &t); rq->tickets[rq->usedContracts] = toAdd; rq->usedContracts++; return RQ_SUCCESS; }

    Read the article

  • iPhone - UIImage Leak, CGBitmapContextCreateImage Leak

    - by bbullis21
    Alright I am having a world of difficulty tracking down this memory leak. When running this script I do not see any memory leaking, but my objectalloc is climbing. Instruments points to CGBitmapContextCreateImage create_bitmap_data_provider malloc, this takes up 60% of my objectalloc. This code is called several times with a NSTimer. //GET IMAGE FROM RESOURCE DIR NSString * fileLocation = [[NSBundle mainBundle] pathForResource:imgMain ofType:@"jpg"]; NSData * imageData = [NSData dataWithContentsOfFile:fileLocation]; UIImage * blurMe = [UIImage imageWithData:imageData]; NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; UIImage * scaledImage = [blurMe _imageScaledToSize:CGSizeMake(blurMe.size.width / dblBlurLevel, blurMe.size.width / dblBlurLevel) interpolationQuality:3.0]; UIImage * labelImage = [scaledImage _imageScaledToSize:blurMe.size interpolationQuality:3.0]; UIImage * imageCopy = [[UIImage alloc] initWithCGImage:labelImage.CGImage]; [pool drain]; // deallocates scaledImage and labelImage imgView.image = imageCopy; [imageCopy release]; Below is the blur function. I believe the objectalloc issue is located in here. Maybe I just need a pair of fresh eyes. Would be great if someone could figure this out. Sorry it is kind of long... I'll try and shorten it. @implementation UIImage(Blur) - (UIImage *)blurredCopy:(int)pixelRadius { //VARS unsigned char *srcData, *destData, *finalData; CGContextRef context = NULL; CGColorSpaceRef colorSpace; void * bitmapData; int bitmapByteCount; int bitmapBytesPerRow; //IMAGE SIZE size_t pixelsWide = CGImageGetWidth(self.CGImage); size_t pixelsHigh = CGImageGetHeight(self.CGImage); bitmapBytesPerRow = (pixelsWide * 4); bitmapByteCount = (bitmapBytesPerRow * pixelsHigh); colorSpace = CGColorSpaceCreateDeviceRGB(); if (colorSpace == NULL) { return NULL; } bitmapData = malloc( bitmapByteCount ); if (bitmapData == NULL) { CGColorSpaceRelease( colorSpace ); } context = CGBitmapContextCreate (bitmapData, pixelsWide, pixelsHigh, 8, bitmapBytesPerRow, colorSpace, kCGImageAlphaPremultipliedFirst ); if (context == NULL) { free (bitmapData); } CGColorSpaceRelease( colorSpace ); free (bitmapData); if (context == NULL) { return NULL; } //PREPARE BLUR size_t width = CGBitmapContextGetWidth(context); size_t height = CGBitmapContextGetHeight(context); size_t bpr = CGBitmapContextGetBytesPerRow(context); size_t bpp = (CGBitmapContextGetBitsPerPixel(context) / 8); CGRect rect = {{0,0},{width,height}}; CGContextDrawImage(context, rect, self.CGImage); // Now we can get a pointer to the image data associated with the bitmap // context. srcData = (unsigned char *)CGBitmapContextGetData (context); if (srcData != NULL) { size_t dataSize = bpr * height; finalData = malloc(dataSize); destData = malloc(dataSize); memcpy(finalData, srcData, dataSize); memcpy(destData, srcData, dataSize); int sums[5]; int i, x, y, k; int gauss_sum=0; int radius = pixelRadius * 2 + 1; int *gauss_fact = malloc(radius * sizeof(int)); for (i = 0; i < pixelRadius; i++) { .....blah blah blah... THIS IS JUST LONG CODE THE CREATES INT FIGURES ........blah blah blah...... } if (gauss_fact) { free(gauss_fact); } } size_t bitmapByteCount2 = bpr * height; //CREATE DATA PROVIDER CGDataProviderRef dataProvider = CGDataProviderCreateWithData(NULL, srcData, bitmapByteCount2, NULL); //CREATE IMAGE CGImageRef cgImage = CGImageCreate( width, height, CGBitmapContextGetBitsPerComponent(context), CGBitmapContextGetBitsPerPixel(context), CGBitmapContextGetBytesPerRow(context), CGBitmapContextGetColorSpace(context), CGBitmapContextGetBitmapInfo(context), dataProvider, NULL, true, kCGRenderingIntentDefault ); //RELEASE INFORMATION CGDataProviderRelease(dataProvider); CGContextRelease(context); if (destData) { free(destData); } if (finalData) { free(finalData); } if (srcData) { free(srcData); } UIImage *retUIImage = [UIImage imageWithCGImage:cgImage]; CGImageRelease(cgImage); return retUIImage; } The only thing I can think of that is holding up the objectalloc is this UIImage *retUIImage = [UIImage imageWithCGImage:cgImage];...but how to do I release that after it has been returned? Hopefully someone can help please.

    Read the article

  • C -Segmentation fault !

    - by FILIaS
    It seems at least weird to me... The program runs normally.But after I call the enter() function for the 4th time,there is a segmentation fault!I would appreciate any help. With the following function enter() I wanna add user commands' datas to a list. [Some part of the code is already posted on another question of me, but I think I should post it again...as it's a different problem I'm facing now.] /* struct for all the datas that user enters on file*/ typedef struct catalog { char short_name[50]; char surname[50]; signed int amount; char description[1000]; struct catalog *next; }catalog,*catalogPointer; catalogPointer current; catalogPointer head = NULL; void enter(void) //user command: i <name> <surname> <amount> <description> { int n,j=2,k=0; char temp[1500]; char *short_name,*surname,*description; signed int amount; char* params = strchr(command,' ') + 1; //strchr returns a pointer to the 1st space on the command.U want a pointer to the char right after that space. strcpy(temp, params); //params is saved as temp. char *curToken = strtok(temp," "); //strtok cuts 'temp' into strings between the spaces and saves them to 'curToken' printf("temp is:%s \n",temp); printf("\nWhat you entered for saving:\n"); for (n = 0; curToken; ++n) //until curToken ends: { if (curToken) { short_name = malloc(strlen(curToken) + 1); strncpy(short_name, curToken, sizeof (short_name)); } printf("Short Name: %s \n",short_name); curToken = strtok(NULL," "); if (curToken) { surname = malloc(strlen(curToken) + 1); strncpy(surname, curToken,sizeof (surname)); } printf("SurName: %s \n",surname); curToken = strtok(NULL," "); if (curToken) { //int * amount= malloc(sizeof (signed int *)); char *chk; amount = (int) strtol(curToken, &chk, 10); if (!isspace(*chk) && *chk != 0) fprintf(stderr,"Warning: expected integer value for amount, received %s instead\n",curToken); } printf("Amount: %d \n",amount); curToken = strtok(NULL,"\0"); if (curToken) { description = malloc(strlen(curToken) + 1); strncpy(description, curToken, sizeof (description)); } printf("Description: %s \n",description); break; } if (findEntryExists(head, surname,short_name) != NULL) //call function in order to see if entry exists already on the catalog printf("\nAn entry for <%s %s> is already in the catalog!\nNew entry not entered.\n",short_name,surname); else { printf("\nTry to entry <%s %s %d %s> in the catalog list!\n",short_name,surname,amount,description); newEntry(&head,short_name,surname,amount,description); printf("\n**Entry done!**\n"); } // Maintain the list in alphabetical order by surname. } catalogPointer findEntryExists (catalogPointer head, char num[],char first[]) { catalogPointer p = head; while (p != NULL && strcmp(p->surname, num) != 0 && strcmp(p->short_name,first) != 0) { p = p->next; } return p; } catalogPointer newEntry (catalog** headRef,char short_name[], char surname[], signed int amount, char description[]) { catalogPointer newNode = (catalogPointer)malloc(sizeof(catalog)); catalogPointer first; catalogPointer second; catalogPointer tmp; first=head; second=NULL; strcpy(newNode->short_name, short_name); strcpy(newNode->surname, surname); newNode->amount=amount; strcpy(newNode->description, description); while (first!=NULL) { if (strcmp(surname,first->surname)>0) second=first; else if (strcmp(surname,first->surname)==0) { if (strcmp(short_name,first->short_name)>0) second=first; } first=first->next; } if (second==NULL) { newNode->next=head; head=newNode; } else //SEGMENTATION APPEARS WHEN IT GETS HERE! { tmp=second->next; newNode->next=tmp; first->next=newNode; } } UPDATE: SegFault appears only when it gets on the 'else' loop of InsertSort() function. I observed that segmentation fault appears when i try to put on the list names that are after it. For example, if in the list exists: [Name:b Surname:b Amount:6 Description:b] [Name:c Surname:c Amount:5 Description:c] [Name:d Surname:d Amount:4 Description:d] [Name:e Surname:e Amount:3 Description:e] [Name:g Surname:g Amount:2 Description:g] [Name:x Surname:x Amount:1 Description:x] and i put: " x z 77 gege" there is a segmentation but if i put "x a 77 gege" it continues normally....

    Read the article

  • C -Segmentation fault after the 4th call of the function!

    - by FILIaS
    It seems at least weird to me... The program runs normally.But after I call the enter() function for the 4th time,there is a segmentation fault!I would appreciate any help. With the following function enter() I wanna add user commands' datas to a list. [Some part of the code is already posted on another question of me, but I think I should post it again...as it's a different problem I'm facing now.] /* struct for all the datas that user enters on file*/ typedef struct catalog { char short_name[50]; char surname[50]; signed int amount; char description[1000]; struct catalog *next; }catalog,*catalogPointer; catalogPointer current; catalogPointer head = NULL; void enter(void) //user command: i <name> <surname> <amount> <description> { int n,j=2,k=0; char temp[1500]; char *short_name,*surname,*description; signed int amount; char* params = strchr(command,' ') + 1; //strchr returns a pointer to the 1st space on the command.U want a pointer to the char right after that space. strcpy(temp, params); //params is saved as temp. char *curToken = strtok(temp," "); //strtok cuts 'temp' into strings between the spaces and saves them to 'curToken' printf("temp is:%s \n",temp); printf("\nWhat you entered for saving:\n"); for (n = 0; curToken; ++n) //until curToken ends: { if (curToken) { short_name = malloc(strlen(curToken) + 1); strncpy(short_name, curToken, sizeof (short_name)); } printf("Short Name: %s \n",short_name); curToken = strtok(NULL," "); if (curToken) { surname = malloc(strlen(curToken) + 1); strncpy(surname, curToken,sizeof (surname)); } printf("SurName: %s \n",surname); curToken = strtok(NULL," "); if (curToken) { //int * amount= malloc(sizeof (signed int *)); char *chk; amount = (int) strtol(curToken, &chk, 10); if (!isspace(*chk) && *chk != 0) fprintf(stderr,"Warning: expected integer value for amount, received %s instead\n",curToken); } printf("Amount: %d \n",amount); curToken = strtok(NULL,"\0"); if (curToken) { description = malloc(strlen(curToken) + 1); strncpy(description, curToken, sizeof (description)); } printf("Description: %s \n",description); break; } if (findEntryExists(head, surname,short_name) != NULL) //call function in order to see if entry exists already on the catalog printf("\nAn entry for <%s %s> is already in the catalog!\nNew entry not entered.\n",short_name,surname); else { printf("\nTry to entry <%s %s %d %s> in the catalog list!\n",short_name,surname,amount,description); newEntry(&head,short_name,surname,amount,description); printf("\n**Entry done!**\n"); } // Maintain the list in alphabetical order by surname. } catalogPointer findEntryExists (catalogPointer head, char num[],char first[]) { catalogPointer p = head; while (p != NULL && strcmp(p->surname, num) != 0 && strcmp(p->short_name,first) != 0) { p = p->next; } return p; } catalogPointer newEntry (catalog** headRef,char short_name[], char surname[], signed int amount, char description[]) { catalogPointer newNode = (catalogPointer)malloc(sizeof(catalog)); catalogPointer first; catalogPointer second; catalogPointer tmp; first=head; second=NULL; strcpy(newNode->short_name, short_name); strcpy(newNode->surname, surname); newNode->amount=amount; strcpy(newNode->description, description); //SEGMENTATION ON THE 4TH RUN OF PROGRAM STOPS HERE depending on the names each time it gets! while (first!=NULL) { if (strcmp(surname,first->surname)>0) second=first; else if (strcmp(surname,first->surname)==0) { if (strcmp(short_name,first->short_name)>0) second=first; } first=first->next; } if (second==NULL) { newNode->next=head; head=newNode; } else { tmp=second->next; newNode->next=tmp; first->next=newNode; } }

    Read the article

  • How do I work around the GCC "error: cast from ‘SourceLocation*’ to ‘int’ loses precision" error when compiling cmockery.c?

    - by Daryl Spitzer
    I need to add unit tests using Cmockery to an existing build environment that uses as hand-crafted Makefile. So I need to figure out how to build cmockery.c (without automake). When I run: g++ -DHAVE_CONFIG_H -DPIC -I ../cmockery-0.1.2 -I /usr/include/malloc -c ../cmockery-0.1.2/cmockery.c -o obj/cmockery.o I get a long list of errors like this: ../cmockery-0.1.2/cmockery.c: In function ‘void initialize_source_location(SourceLocation*)’: ../cmockery-0.1.2/cmockery.c:248: error: cast from ‘SourceLocation*’ to ‘int’ loses precision Here are lines 247:248 of cmockery.c: static void initialize_source_location(SourceLocation * const location) { assert_true(location); assert_true is defined on line 154 of cmockery.h: #define assert_true(c) _assert_true((int)(c), #c, __FILE__, __LINE__) So the problem (as the error states) is GCC doesn't like the cast from ‘SourceLocation*’ to ‘int’. I can build Cmockery using ./configure and make (on Linux, and on Mac OS X if I export CFLAGS=-I/usr/include/malloc first), without any errors. I've tried looking at the command-line that compiles cmockery.c when I run make (after ./configure): gcc -DHAVE_CONFIG_H -I. -I. -I./src -I./src -Isrc/google -I/usr/include/malloc -MT libcmockery_la-cmockery.lo -MD -MP -MF .deps/libcmockery_la-cmockery.Tpo -c src/cmockery.c -fno-common -DPIC -o .libs/libcmockery_la-cmockery.o ...but I don't see any options that might work around this error. In "error: cast from 'void*' to 'int' loses precision", I see I could change (int) in cmockery.h to (intptr_t). And I've confirmed that works. But since I can build Cmockery with ./configure and make, there must be a way to get it to build without modifying the source.

    Read the article

  • Advice using leaks in instruments for noobs

    - by Gyozo Kudor
    Hello I am pretty new to iphone development. I have run my app for the first time using the "Leaks" from "Instruments". It shows me several leaks around 20 the smallest is 32 bytes and there is one with 1KB. I have followed the memory management guidelines, (i (think i) understand how and when to use release, not to use it when adding to autorelease pools, for every copy, retain, init there should be a release,... etc). I don't think I understand the output of the Leaks in instruments. What does "Responsible library" and "Responsible frame" mean. Because there are some classes and methods i never used directly. Are there any good tutorials for debugging memory leaks in instruments or other advice you can give me regarding leaks. Thanks in advance. Here are the largest 2 leaks. Leaked Object # Address Size Responsible Library Responsible Frame Malloc 1.00 KB 0x4827400 1024 CFNetwork std::vector *, std::allocator * ::reserve(unsigned long) // i have no idea what this is. Leaked Object # Address Size Responsible Library Responsible Frame Malloc 128 Bytes 5 640 UIKit UIImagePickerLoadPhotoLibraryIfNecessary // so this means UIImagePicker is leaking memory? The first leak i get Leaked Object # Address Size Responsible Library Responsible Frame Malloc 128 Bytes 0x442dfd0 128 UIKit UIKeyboardInputManagerClassForInputMode I don't understand any of those.

    Read the article

  • A queue in C using structs and dynamic memory allocation (linked list)

    - by Martin Pugh
    I am tasked with making a queue data structure in C, as a linked list. Our lecturer gave us a large amount of code to implement a stack, but we have to adapt it to create a queue. The code our lecturer gave us ends up not compiling and segfaulting at the exact same point as the code I wrote for the queue. I'm very new to structs, malloc and C in general, so there could be something painfully obvious I've overlooked. Here is the code I am using: #include <stdio.h> #include <stdlib.h> struct node{ int data; //contains the actual data struct node *prev; //pointer to previous node (Closer to front) struct node *next; //pointer to next node (Closer to back) }; typedef struct node *Nodepointer; struct queue{ Nodepointer front; Nodepointer back; }; typedef struct queue *Queuepointer; main(){ Queuepointer myqueue; //create a queue called myqueue init(myqueue); //initialise the queue Nodepointer new = (Nodepointer)malloc(sizeof(struct node)); myqueue->front = new; } int init(Queuepointer q){ q = (Queuepointer)malloc(sizeof(struct queue)); q->front = NULL; q->back = NULL; } The idea is that the queue struct 'contains' the first and last nodes in a queue, and when a node is created, myqueue is updated. However, I cannot even get to that part (pop and push are written but omitted for brevity). The code is segfaulting at the line myqueue->front = new; with the following gdb output: Program received signal SIGSEGV, Segmentation fault. 0x08048401 in main () at queue.c:27 27 myqueue->front = new; Any idea what I'm doing wrong?

    Read the article

  • Memory Leaks when touching UITableViewCells and poping off view.

    - by Falcon
    Hi All, I'm currently having a problem where the leaks tool is reporting a slew of memory leaks after clicking on cells within a UITableView and then hitting the back button and popping off the view. Majority of the leaks reported can not be traced back to any specific location in my code, they are: Leaked Object # Address Size Responsible Library Responsible Frame NSCFArray 2 < multiple > 64 UIKit -[UITouch(UITouchInternal) UITouch 2 < multiple > 128 GraphicsServices PurpleEventCallback Malloc 48 Bytes 2 < multiple > 96 Foundation -[NSCFArray insertObject:atIndex:] UIDelayedAction 2 < multiple > 96 UIKit -[UILongPressGestureRecognizer startTimer] NSCFArray 2 < multiple > 64 UIKit -[UILongPressGestureRecognizer touchesBegan:withEvent:] Malloc 32 Bytes 2 < multiple > 64 Foundation -[NSCFArray insertObject:atIndex:] Malloc 16 Bytes 2 < multiple > 32 Foundation -[NSCFSet unionSet:] Now I have commented out all my code in any touch event functions that I have written and it still leaks if I click on the cell a few times and then hit the back button to return to the previous view. Any ideas on what might actually be the problem here? Thanks,

    Read the article

  • Inorder tree traversal in binary tree in C

    - by srk
    In the below code, I'am creating a binary tree using insert function and trying to display the inserted elements using inorder function which follows the logic of In-order traversal.When I run it, numbers are getting inserted but when I try the inorder function( input 3), the program continues for next input without displaying anything. I guess there might be a logical error.Please help me clear it. Thanks in advance... #include<stdio.h> #include<stdlib.h> int i; typedef struct ll { int data; struct ll *left; struct ll *right; } node; node *root1=NULL; // the root node void insert(node *root,int n) { if(root==NULL) //for the first(root) node { root=(node *)malloc(sizeof(node)); root->data=n; root->right=NULL; root->left=NULL; } else { if(n<(root->data)) { root->left=(node *)malloc(sizeof(node)); insert(root->left,n); } else if(n>(root->data)) { root->right=(node *)malloc(sizeof(node)); insert(root->right,n); } else { root->data=n; } } } void inorder(node *root) { if(root!=NULL) { inorder(root->left); printf("%d ",root->data); inorder(root->right); } } main() { int n,choice=1; while(choice!=0) { printf("Enter choice--- 1 for insert, 3 for inorder and 0 for exit\n"); scanf("%d",&choice); switch(choice) { case 1: printf("Enter number to be inserted\n"); scanf("%d",&n); insert(root1,n); break; case 3: inorder(root1); break; default: break; } } }

    Read the article

  • Question on passing a pointer to a structure in C to a function?

    - by worlds-apart89
    Below, I wrote a primitive singly linked list in C. Function "addEditNode" MUST receive a pointer by value, which, I am guessing, means we can edit the data of the pointer but can not point it to something else. If I allocate memory using malloc in "addEditNode", when the function returns, can I see the contents of first-next ? Second question is do I have to free first-next or is it only first that I should free? I am running into segmentation faults on Linux. #include <stdio.h> #include <stdlib.h> typedef struct list_node list_node_t; struct list_node { int value; list_node_t *next; }; void addEditNode(list_node_t *node) { node->value = 10; node->next = (list_node_t*) malloc(sizeof(list_node_t)); node->next->value = 1; node->next->next = NULL; } int main() { list_node_t *first = (list_node_t*) malloc(sizeof(list_node_t)); first->value = 1; first->next = NULL; addEditNode(first); free(first); return 0; }

    Read the article

  • Determining presence of prototype with correct return type

    - by R..
    Here's a random problem in C black magic I just came up with: Write a function that returns 1 if malloc has been prototyped to return a pointer type and 0 if malloc has a return type of int (either implicitly or due to wrong prototype), without invoking any implementation-defined or undefined behavior. I believe it's solvable, but I haven't worked out the solution. Note that calling the function cannot be necessary and in fact is not possible since calling a function with the incorrect prototype is undefined behavior. I have some ideas for ingredients but I think it makes for a better puzzle (and possibly more diverse ideas) if I leave them out for now. I don't need the solution for any immediate use, but it could be handy in configure scripts and such. Update: A better example of the usefulness (with strdup instead of malloc): #undef strdup #define strdup(x) (strdup_has_proto ? strdup((x)) : my_strdup((x))) i.e. being able to implement X_has_proto as an expression at the source level could be a portable way to use functions which a system might or might not have, and fall back on a local replacement, without needing any separate configure step.

    Read the article

  • Problem with passing array of pointers to struct among functions in C

    - by karatemonkey
    The Code that follows segfaults on the call to strncpy and I can't see what I am doing wrong. I need another set of eyes to look it this. Essentially I am trying to alloc memory for a struct that is pointed to by an element in a array of pointers to struct. #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_POLICY_NAME_SIZE 64 #define POLICY_FILES_TO_BE_PROCESSED "SPFPolicyFilesReceivedOffline\0" typedef struct TarPolicyPair { int AppearanceTime; char *IndividualFile; char *FullPolicyFile; } PolicyPair; enum { bwlist = 0, fzacts, atksig, rules, MaxNumberFileTypes }; void SPFCreateIndividualPolicyListing(PolicyPair *IndividualPolicyPairtoCreate ) { IndividualPolicyPairtoCreate = (PolicyPair *) malloc(sizeof(PolicyPair)); IndividualPolicyPairtoCreate->IndividualFile = (char *)malloc((MAX_POLICY_NAME_SIZE * sizeof(char))); IndividualPolicyPairtoCreate->FullPolicyFile = (char *)malloc((MAX_POLICY_NAME_SIZE * sizeof(char))); IndividualPolicyPairtoCreate->AppearanceTime = 0; memset(IndividualPolicyPairtoCreate->IndividualFile, '\0', (MAX_POLICY_NAME_SIZE * sizeof(char))); memset(IndividualPolicyPairtoCreate->FullPolicyFile, '\0', (MAX_POLICY_NAME_SIZE * sizeof(char))); } void SPFCreateFullPolicyListing(SPFPolicyPair **CurrentPolicyPair, char *PolicyName, char *PolicyRename) { int i; for(i = 0; i < MaxNumberFileTypes; i++) { CreateIndividualPolicyListing((CurrentPolicyPair[i])); // segfaults on this call strncpy((*CurrentPolicyPair)[i].IndividualFile, POLICY_FILES_TO_BE_PROCESSED, (SPF_POLICY_NAME_SIZE * sizeof(char))); } } int main() { SPFPolicyPair *CurrentPolicyPair[MaxNumberFileTypes] = {NULL, NULL, NULL, NULL}; int i; CreateFullPolicyListing(&CurrentPolicyPair, POLICY_FILES_TO_BE_PROCESSED, POLICY_FILES_TO_BE_PROCESSED); return 0; }

    Read the article

  • Using memset on structures in C++

    - by garry
    Hey guys. I am working on fixing older code for my job. It is currently written in C++. They converted static allocation to dynamic but didn't edit the memsets/memcmp/memcpy. This is my first programming internship so bare with my newbe-like question. The following code is in C, but I want to have it in C++ ( I read that malloc isn't good practice in C++). I have two scenarios: First, we have f created. Then you use &f in order to fill with zero. The second is a pointer *pf. I'm not sure how to set pf to all 0's like the previous example in C++. Could you just do pf = new foo instead of malloc and then call memset(pf, 0, sizeof(foo))? struct foo { ... } f; memset( &f, 0, sizeof(f) ); //or struct foo { ... } *pf; pf = (struct foo*) malloc( sizeof(*pf) ); memset( pf, 0, sizeof(*pf) );

    Read the article

  • Initialize void pointer to point to an array

    - by idealistikz
    Suppose I have the following: typedef struct { int itemSize; int count; void *list; } Mystruct; Mystruct *InitStruct(int itemSize, int count) { Mystruct *my = malloc(sizeof(Mystruct)); my->itemSize = itemSize; my->count = count; //What is the best way to initialize list? For example: //my->list = malloc(count * sizeof(void *)); OR //my->list = malloc(count * sizeof(itemSize)); } //The following should return a pointer to the element stored at a given index void *Retrieve(const MyStruct *my, int index) { void *item; //What is the best way to return a pointer to the item at the given index from //my->list? } Mystruct is similar to an array and void *list is supposed to store the elements or pointers to the elements. Mystruct *InitStruct is a function that initializes a Mystruct pointer and void *Retrieve is a function that returns a pointer to the element stored at a given index. First, how should I initialize void* list? Should it hold the actual elements or be an array of pointers pointing to the elements? Second, using the void *Retrieve function, how do I return a pointer to the element stored at a given index in my-list?

    Read the article

  • C code Error: free(): invalid next size (fast):

    - by user1436057
    I got an error from my code, but I'm not sure where to fix it. Here's the explanation of what my code does: I'm writing some code that will read an input file and store each line as an object (char type) in an array. The first line of the input file is a number. This number tells me how many lines that I should read and store in the array. Here's my code: int main(int argc, char *argv[]){ FILE *fp; char **path; int num, i; ... /*after reading the first line and store the number value in num*/ path = malloc(num *sizeof(char)); i=0; while (!feof(fp)) { char buffer[500]; int length = 0; for (ch = fgetc(fp); ch != EOF && ch != '\n'; ch = fgetc(fp)) { buffer[length++] = ch; } if(ch == '\n' && ch!= EOF){ buffer[length] = '\0'; path[i] = malloc(strlen(buffer)+1); strcpy(path[i], buffer); i++; } } ... free(path); } After running the code, I get this *** glibc detected *** free(): invalid next size (fast): I have searched around and know this is malloc/free error, but I don't exactly know to fix it. Any help would be great. Thanks!

    Read the article

  • Please help me debug this little C program on dynamic two-dimensional array? [migrated]

    - by azhi
    I am a newbie here. I have written a little C program, which is to create a two-dimensional matrix. Here is the code: #include <stdio.h> #include <stdlib.h> int **CreatMatrix(int m,int n){ int **Matrix; int i; Matrix=(int**)malloc(m*sizeof(int*)); for(i=0;i<m;i++){ Matrix[i]=(int*)malloc(n*sizeof(int)); } return Matrix; } int main(){ int m,n; int **A; printf("Please input the size of the Matrix: "); scanf("%d%d",&m,&n); A=CreatMatrix(m,n); printf("Please input the entries of the Matrix, which should be integers!\n"); int i,j; for(i=0;i<m;i++){ for(j=0;j<n;j++){ scanf("%d",&A[i][j]); } } printf("The Matrix that you input is:\n"); for(i=0;i<m;i++){ for(j=0;j<n;j++){ printf("%3d ",A[i][j]); } printf("\n"); } for(i=0;i<m;i++) free(A[i]); free(A); } I have run it, and it works fine. But I am not sure if it is right? Can anyone help me debug it?

    Read the article

  • Free memory outside function [migrated]

    - by Dev Bag
    Can you please help with this issue, is the below gonna leak memory or is it ok? and please let me know if there is something else that I need to pay attention to typedef struct { int len; UC * message; }pack; pack * prepare_packet_to_send(const int length,const unsigned char tag,const int numargs, ... ) { pack *layer= malloc(sizeof(pack)); va_list listp; va_start( listp, numargs ); int step = 0; layer->message = (unsigned char *) malloc(length); layer->len = length; int i = 0; int len = 0; unsigned char *source_message ; for( i = 0 ; i < numargs; i++ ) { source_message = va_arg( listp, unsigned char *); len = va_arg( listp, long); memcpy(layer->message+step, source_message, (long) len); step+=len; } va_end( listp ); return layer; } main() { pack *test = call prepare_packet_to_send(sizeof(var1)+sizeof(var2),any tag,any args) // are following two frees correct/enough? or is there something else i need to do to prevent mem leak? free(test->message); free(test); }

    Read the article

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