/** Try to find the specified file in any of the possible directories where mime files can be located. This code is shamelessly stolen from xdg_run_command_on_dirs. \param list Full file paths will be appended to this list. \param f The relative filename search for the the data directories. \param all If zero, then stop after the first filename. \return The number of filenames added to the list. */ static int append_filenames( string_list_t &list, const char *f, int all ) { size_t prev_count = list.size(); char *result; const char *xdg_data_home; const char *xdg_data_dirs; const char *ptr; xdg_data_home = getenv ("XDG_DATA_HOME"); if (xdg_data_home) { result = file_exists( xdg_data_home, f ); if (result) { list.push_back(result); if ( !all ) return 1; } } else { const char *home; home = getenv ("HOME"); if (home != NULL) { char *guessed_xdg_home; guessed_xdg_home = (char *)my_malloc (strlen (home) + strlen ("/.local/share") + 1); if( !guessed_xdg_home ) return 0; strcpy (guessed_xdg_home, home); strcat (guessed_xdg_home, "/.local/share"); result = file_exists( guessed_xdg_home, f ); free (guessed_xdg_home); if (result) { list.push_back(result); if ( !all ) return 1; } } } xdg_data_dirs = getenv ("XDG_DATA_DIRS"); if (xdg_data_dirs == NULL) xdg_data_dirs = "/usr/local/share:/usr/share"; ptr = xdg_data_dirs; while (*ptr != '\000') { const char *end_ptr; char *dir; int len; end_ptr = ptr; while (*end_ptr != ':' && *end_ptr != '\000') end_ptr ++; if (end_ptr == ptr) { ptr++; continue; } len = end_ptr - ptr; dir = (char *)my_malloc (len + 1); if( !dir ) return 0; strncpy (dir, ptr, len); dir[len] = '\0'; result = file_exists( dir, f ); free (dir); if (result) { list.push_back(result); if ( !all ) { return 1; } } ptr = end_ptr; } return list.size() - prev_count; }
MY_DIR *my_dir(const char *path, myf MyFlags) { struct fileinfo *fnames; char *buffer, *obuffer, *tempptr; int eof,i,fcnt,firstfcnt,length,maxfcnt; uint size; #ifdef __BORLANDC__ struct ffblk find; #else struct _finddata_t find; #endif ushort mode; char tmp_path[FN_REFLEN],*tmp_file,attrib; my_ptrdiff_t diff; #ifdef _WIN64 __int64 handle; #else long handle; #endif DBUG_ENTER("my_dir"); DBUG_PRINT("my",("path: '%s' stat: %d MyFlags: %d",path,MyFlags)); /* Put LIB-CHAR as last path-character if not there */ tmp_file=tmp_path; if (!*path) *tmp_file++ ='.'; /* From current dir */ tmp_file= strmov(tmp_file,path); if (tmp_file[-1] == FN_DEVCHAR) *tmp_file++= '.'; /* From current dev-dir */ if (tmp_file[-1] != FN_LIBCHAR) *tmp_file++ =FN_LIBCHAR; tmp_file[0]='*'; /* MSDOS needs this !??? */ tmp_file[1]='.'; tmp_file[2]='*'; tmp_file[3]='\0'; #ifdef __BORLANDC__ if ((handle= findfirst(tmp_path,&find,0)) == -1L) goto error; #else if ((handle=_findfirst(tmp_path,&find)) == -1L) goto error; #endif size = STARTSIZE; firstfcnt = maxfcnt = (size - sizeof(MY_DIR)) / (sizeof(struct fileinfo) + FN_LEN); if ((buffer = (char *) my_malloc(size, MyFlags)) == 0) goto error; fnames= (struct fileinfo *) (buffer + sizeof(MY_DIR)); tempptr = (char *) (fnames + maxfcnt); fcnt = 0; for (;;) { do { fnames[fcnt].name = tempptr; #ifdef __BORLANDC__ tempptr = strmov(tempptr,find.ff_name) + 1; fnames[fcnt].mystat.st_size=find.ff_fsize; fnames[fcnt].mystat.st_uid=fnames[fcnt].mystat.st_gid=0; mode=MY_S_IREAD; attrib=find.ff_attrib; #else tempptr = strmov(tempptr,find.name) + 1; fnames[fcnt].mystat.st_size=find.size; fnames[fcnt].mystat.st_uid=fnames[fcnt].mystat.st_gid=0; mode=MY_S_IREAD; attrib=find.attrib; #endif if (!(attrib & _A_RDONLY)) mode|=MY_S_IWRITE; if (attrib & _A_SUBDIR) mode|=MY_S_IFDIR; fnames[fcnt].mystat.st_mode=mode; #ifdef __BORLANDC__ fnames[fcnt].mystat.st_mtime=((uint32) find.ff_ftime); #else fnames[fcnt].mystat.st_mtime=((uint32) find.time_write); #endif ++fcnt; #ifdef __BORLANDC__ } while ((eof= findnext(&find)) == 0 && fcnt < maxfcnt); #else } while ((eof= _findnext(handle,&find)) == 0 && fcnt < maxfcnt); #endif DBUG_PRINT("test",("eof: %d errno: %d",eof,errno)); if (eof) break; size += STARTSIZE; obuffer = buffer; if (!(buffer = (char *) my_realloc((gptr) buffer, size, MyFlags | MY_FREE_ON_ERROR))) goto error; length= sizeof(struct fileinfo ) * firstfcnt; diff= PTR_BYTE_DIFF(buffer , obuffer) +length; fnames= (struct fileinfo *) (buffer + sizeof(MY_DIR)); tempptr= ADD_TO_PTR(tempptr,diff,char*); for (i = 0; i < maxfcnt; i++) fnames[i].name = ADD_TO_PTR(fnames[i].name,diff,char*); /* move filenames upp a bit */ maxfcnt += firstfcnt; bmove_upp(tempptr,ADD_TO_PTR(tempptr,-length,char*), (int) PTR_BYTE_DIFF(tempptr,fnames+maxfcnt)); }
TREE_ELEMENT *tree_insert(TREE *tree, void *key, uint key_size, void* custom_arg) { int cmp; TREE_ELEMENT *element,***parent; parent= tree->parents; *parent = &tree->root; element= tree->root; for (;;) { if (element == &tree->null_element || (cmp = (*tree->compare)(custom_arg, ELEMENT_KEY(tree,element), key)) == 0) break; if (cmp < 0) { *++parent= &element->right; element= element->right; } else { *++parent = &element->left; element= element->left; } } if (element == &tree->null_element) { uint alloc_size=sizeof(TREE_ELEMENT)+key_size+tree->size_of_element; tree->allocated+=alloc_size; if (tree->memory_limit && tree->elements_in_tree && tree->allocated > tree->memory_limit) { reset_tree(tree); return tree_insert(tree, key, key_size, custom_arg); } key_size+=tree->size_of_element; if (tree->with_delete) element=(TREE_ELEMENT *) my_malloc(alloc_size, MYF(MY_WME)); else element=(TREE_ELEMENT *) alloc_root(&tree->mem_root,alloc_size); if (!element) return(NULL); **parent=element; element->left=element->right= &tree->null_element; if (!tree->offset_to_key) { if (key_size == sizeof(void*)) /* no length, save pointer */ *((void**) (element+1))=key; else { *((void**) (element+1))= (void*) ((void **) (element+1)+1); memcpy((uchar*) *((void **) (element+1)),key, (size_t) (key_size-sizeof(void*))); } } else memcpy((uchar*) element+tree->offset_to_key,key,(size_t) key_size); element->count=1; /* May give warning in purify */ tree->elements_in_tree++; rb_insert(tree,parent,element); /* rebalance tree */ } else { if (tree->flag & TREE_NO_DUPS) return(NULL); element->count++; /* Avoid a wrap over of the count. */ if (! element->count) element->count--; } DBUG_EXECUTE("check_tree", test_rb_tree(tree->root););
int SVMLightRunner::librarySVMClassifyMain( int argc, char **argv, bool use_gmumr, SVMConfiguration &config ) { LOG( config.log, LogLevel::DEBUG_LEVEL, __debug_prefix__ + ".librarySVMClassifyMain() Started." ); DOC *doc; /* test example */ WORD *words; long max_docs,max_words_doc,lld; long totdoc=0,queryid,slackid; long correct=0,incorrect=0,no_accuracy=0; long res_a=0,res_b=0,res_c=0,res_d=0,wnum,pred_format; long j; double t1,runtime=0; double dist,doc_label,costfactor; char *line,*comment; FILE *predfl,*docfl; MODEL *model; // GMUM.R changes { librarySVMClassifyReadInputParameters( argc, argv, docfile, modelfile, predictionsfile, &verbosity, &pred_format, use_gmumr, config); if (!use_gmumr) { nol_ll(docfile,&max_docs,&max_words_doc,&lld); /* scan size of input file */ lld+=2; line = (char *)my_malloc(sizeof(char)*lld); } else { max_docs = config.target.n_rows; max_words_doc = config.getDataDim(); config.result = arma::zeros<arma::vec>(max_docs); // Prevent writing to the file pred_format = -1; // lld used only for file reading } max_words_doc+=2; words = (WORD *)my_malloc(sizeof(WORD)*(max_words_doc+10)); // GMUM.R changes } model=libraryReadModel(modelfile, use_gmumr, config); // GMUM.R changes } if(model->kernel_parm.kernel_type == 0) { /* linear kernel */ /* compute weight vector */ add_weight_vector_to_linear_model(model); } if(verbosity>=2) { C_PRINTF("Classifying test examples.."); C_FFLUSH(stdout); } // GMUM.R changes { bool newline; if (!use_gmumr) { if ((predfl = fopen (predictionsfile, "w")) == NULL) { perror (predictionsfile); EXIT (1); } if ((docfl = fopen (docfile, "r")) == NULL) { perror (docfile); EXIT (1); } newline = (!feof(docfl)) && fgets(line,(int)lld,docfl); } else { newline = false; if (totdoc < config.getDataExamplesNumber()) { newline = true; std::string str = SVMConfigurationToSVMLightLearnInputLine(config, totdoc); line = new char[str.size() + 1]; std::copy(str.begin(), str.end(), line); line[str.size()] = '\0'; } } while(newline) { if (use_gmumr) { std::string stringline = ""; } // GMUM.R changes } if(line[0] == '#') continue; /* line contains comments */ parse_document(line,words,&doc_label,&queryid,&slackid,&costfactor,&wnum, max_words_doc,&comment); totdoc++; if(model->kernel_parm.kernel_type == 0) { /* linear kernel */ for(j=0;(words[j]).wnum != 0;j++) { /* Check if feature numbers */ if((words[j]).wnum>model->totwords) /* are not larger than in */ (words[j]).wnum=0; /* model. Remove feature if */ } /* necessary. */ doc = create_example(-1,0,0,0.0,create_svector(words,comment,1.0)); t1=get_runtime(); dist=classify_example_linear(model,doc); runtime+=(get_runtime()-t1); free_example(doc,1); } else { /* non-linear kernel */ doc = create_example(-1,0,0,0.0,create_svector(words,comment,1.0)); t1=get_runtime(); dist=classify_example(model,doc); runtime+=(get_runtime()-t1); free_example(doc,1); } if(dist>0) { if(pred_format==0) { /* old weired output format */ C_FPRINTF(predfl,"%.8g:+1 %.8g:-1\n",dist,-dist); } if(doc_label>0) correct++; else incorrect++; if(doc_label>0) res_a++; else res_b++; } else { if(pred_format==0) { /* old weired output format */ C_FPRINTF(predfl,"%.8g:-1 %.8g:+1\n",-dist,dist); } if(doc_label<0) correct++; else incorrect++; if(doc_label>0) res_c++; else res_d++; } if(pred_format==1) { /* output the value of decision function */ C_FPRINTF(predfl,"%.8g\n",dist); } if((int)(0.01+(doc_label*doc_label)) != 1) { no_accuracy=1; } /* test data is not binary labeled */ if(verbosity>=2) { if(totdoc % 100 == 0) { C_PRINTF("%ld..",totdoc); C_FFLUSH(stdout); } } // GMUM.R changes { if (!use_gmumr) { newline = (!feof(docfl)) && fgets(line,(int)lld,docfl); } else { newline = false; // Store prediction result in config config.result[totdoc-1] = dist; // Read next line if (totdoc < config.getDataExamplesNumber()) { newline = true; std::string str = SVMConfigurationToSVMLightLearnInputLine(config, totdoc); line = new char[str.size() + 1]; std::copy(str.begin(), str.end(), line); line[str.size()] = '\0'; } } } if (!use_gmumr) { fclose(predfl); fclose(docfl); free(line); } // GMUM.R changes } free(words); free_model(model,1); if(verbosity>=2) { C_PRINTF("done\n"); /* Note by Gary Boone Date: 29 April 2000 */ /* o Timing is inaccurate. The timer has 0.01 second resolution. */ /* Because classification of a single vector takes less than */ /* 0.01 secs, the timer was underflowing. */ C_PRINTF("Runtime (without IO) in cpu-seconds: %.2f\n", (float)(runtime/100.0)); } if((!no_accuracy) && (verbosity>=1)) { C_PRINTF("Accuracy on test set: %.2f%% (%ld correct, %ld incorrect, %ld total)\n",(float)(correct)*100.0/totdoc,correct,incorrect,totdoc); C_PRINTF("Precision/recall on test set: %.2f%%/%.2f%%\n",(float)(res_a)*100.0/(res_a+res_b),(float)(res_a)*100.0/(res_a+res_c)); } return(0); }
void SVMLightRunner::libraryReadDocuments ( char *docfile, DOC ***docs, double **label, long int *totwords, long int *totdoc, bool use_gmumr, SVMConfiguration &config ) { LOG( config.log, LogLevel::DEBUG_LEVEL, __debug_prefix__ + ".libraryReadDocuments() Started." ); char *line,*comment; WORD *words; long dnum=0,wpos,dpos=0,dneg=0,dunlab=0,queryid,slackid,max_docs; long max_words_doc, ll; double doc_label,costfactor; FILE *docfl; if(verbosity>=1) { C_PRINTF("Scanning examples..."); C_FFLUSH(stdout); } // GMUM.R changes { if (!use_gmumr) { nol_ll(docfile,&max_docs,&max_words_doc,&ll); /* scan size of input file */ } else { max_docs = config.target.n_rows; max_words_doc = config.getDataDim(); // ll used only for file reading } // GMUM.R changes } max_words_doc+=2; ll+=2; max_docs+=2; if(verbosity>=1) { C_PRINTF("done\n"); C_FFLUSH(stdout); } (*docs) = (DOC **)my_malloc(sizeof(DOC *)*max_docs); /* feature vectors */ (*label) = (double *)my_malloc(sizeof(double)*max_docs); /* target values */ // GMUM.R changes { if (!use_gmumr) { line = (char *)my_malloc(sizeof(char)*ll); if ((docfl = fopen (docfile, "r")) == NULL) { perror (docfile); EXIT (1); } } // GMUM.R changes } words = (WORD *)my_malloc(sizeof(WORD)*(max_words_doc+10)); if(verbosity>=1) { C_PRINTF("Reading examples into memory..."); C_FFLUSH(stdout); } dnum=0; (*totwords)=0; // GMUM.R changes { bool newline; if (!use_gmumr) { newline = (!feof(docfl)) && fgets(line,(int)ll,docfl); } else { newline = false; if (dnum < config.target.n_rows) { newline = true; std::string str = SVMConfigurationToSVMLightLearnInputLine(config, dnum); line = new char[str.size() + 1]; std::copy(str.begin(), str.end(), line); line[str.size()] = '\0'; } } while(newline) { if (use_gmumr) { std::string stringline = ""; } // GMUM.R changes } if(line[0] == '#') continue; /* line contains comments */ if(!parse_document(line,words,&doc_label,&queryid,&slackid,&costfactor, &wpos,max_words_doc,&comment)) { C_PRINTF("\nParsing error in line %ld!\n%s",dnum,line); EXIT(1); } (*label)[dnum]=doc_label; /* C_PRINTF("docnum=%ld: Class=%f ",dnum,doc_label); */ if(doc_label > 0) dpos++; if (doc_label < 0) dneg++; if (doc_label == 0) { if(config.use_transductive_learning){ dunlab++; }else{ C_PRINTF("Please for transductive learning pass use_transductive_learning\n"); EXIT(1); } } if((wpos>1) && ((words[wpos-2]).wnum>(*totwords))) (*totwords)=(words[wpos-2]).wnum; if((*totwords) > MAXFEATNUM) { C_PRINTF("\nMaximum feature number exceeds limit defined in MAXFEATNUM!\n"); EXIT(1); } (*docs)[dnum] = create_example(dnum,queryid,slackid,costfactor, create_svector(words,comment,1.0)); /* C_PRINTF("\nNorm=%f\n",((*docs)[dnum]->fvec)->twonorm_sq); */ dnum++; if(verbosity>=1) { if((dnum % 100) == 0) { C_PRINTF("%ld..",dnum); C_FFLUSH(stdout); } } // GMUM.R changes { if (!use_gmumr) { newline = (!feof(docfl)) && fgets(line,(int)ll,docfl); } else { newline = false; if (dnum < config.target.n_rows) { newline = true; std::string str = SVMConfigurationToSVMLightLearnInputLine(config, dnum); line = new char[str.size() + 1]; std::copy(str.begin(), str.end(), line); line[str.size()] = '\0'; } } // GMUM.R changes } } if (!use_gmumr) { fclose(docfl); free(line); }; free(words); if(verbosity>=1) { C_FPRINTF(stdout, "OK. (%ld examples read)\n", dnum); } (*totdoc)=dnum; }
/* data mining hard negative samples */ void data_mining_hard_examples(char *trainfile, char *testfile, STRUCT_LEARN_PARM *sparm, STRUCTMODEL *sm) { int i, j, n, ntrain, ntest, num, object_label, count, count_pos, count_neg; char line[BUFFLE_SIZE]; double *energy, *energies; SAMPLE testsample; LABEL *y = NULL; ENERGYINDEX *energy_index; FILE *fp, *ftrain, *ftest; /* MPI process */ int rank; int procs_num; int start, end, block_size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &procs_num); /* read negative examples */ printf("Reading negative samples for data mining..."); testsample = read_struct_examples(testfile, sparm, sm); printf("Done\n"); n = testsample.n; block_size = (n+procs_num-1) / procs_num; start = rank*block_size; end = start+block_size-1 > n-1 ? n-1 : start+block_size-1; energy = (double*)my_malloc(sizeof(double)*n); energies = (double*)my_malloc(sizeof(double)*n); memset(energy, 0, sizeof(double)*n); memset(energies, 0, sizeof(double)*n); for(i = start; i <= end; i++) { y = classify_struct_example(testsample.examples[i].x, &num, 0, sm, sparm); count = 0; for(j = 0; j < num; j++) { if(y[j].object_label) count++; } printf("Data mining hard negative example %d/%d: %d objects detected\n", i+1, n, count); if(count == 0) energy[i] = -sparm->loss_value; else { for(j = 0; j < num; j++) { if(y[j].object_label) { energy[i] = y[j].energy; break; } } } /* free labels */ for(j = 0; j < num; j++) free_label(y[j]); free(y); } MPI_Allreduce(energy, energies, n, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); if(rank == 0) { energy_index = (ENERGYINDEX*)my_malloc(sizeof(ENERGYINDEX)*n); for(i = 0; i < n; i++) { energy_index[i].index = i; energy_index[i].energy = energies[i]; } /* sort energies */ qsort(energy_index, n, sizeof(ENERGYINDEX), compare_energy); /* construct new training data and write to file */ printf("Writing data to temp.dat...\n"); fp = fopen("temp.dat", "w"); ftrain = fopen(trainfile, "r"); if(ftrain == NULL) { printf("Cannot open file %s to read\n", trainfile); exit(1); } ftest = fopen(testfile, "r"); if(ftest == NULL) { printf("Cannot open file %s to read\n", testfile); exit(1); } /* positive samples from training data file */ fscanf(ftrain, "%d\n", &ntrain); count_pos = ntrain/2; fscanf(ftest, "%d\n", &ntest); if(ntest < ntrain/2) n = ntest + ntrain/2; else n = ntrain; count_neg = n - count_pos; fprintf(fp, "%d\n", n); for(i = 0; i < ntrain; i++) { fgets(line, BUFFLE_SIZE, ftrain); sscanf(line, "%d", &object_label); if(object_label == 1) fputs(line, fp); else break; } fclose(ftrain); /* negative samples from hard negative examples */ count = 0; for(i = 0; i < ntest; i++) { fgets(line, BUFFLE_SIZE, ftest); for(j = 0; j < count_neg; j++) { if(i == energy_index[j].index) { count++; fputs(line, fp); break; } } if(count >= count_neg) break; } fclose(ftest); fclose(fp); free(energy_index); printf("Done\n"); } MPI_Barrier(MPI_COMM_WORLD); free(energy); free(energies); free_struct_sample(testsample); }
/** * \fn Worms* createWorms(const char *file, SDL_Color* couleur) * \brief Créé et initialise une structure worms. * * \param[in] name, chaine de caractères correspondant au nom du worms * \param[in] couleur, couleur de l'équipe du worms * * \returns pointeur vers la structure worms créée, NULL si echec */ Worms* createWorms(Equipe* team, char* name, SDL_Color* couleur) { Worms* worms = NULL; SDL_Surface* moveRight = NULL; SDL_Surface* moveLeft = NULL; SDL_Rect clip = initRect(445, 28, WIDTHSPRITEMOVE, HIGHTSPRITEMOVE); char strVie[10]; fprintf(logFile, "createWorms : START :\n\n"); worms = (Worms*)my_malloc(sizeof(Worms)); if (worms == NULL) { fprintf(logFile, "createWorms : FAILURE, allocating memory to worms.\n\n"); decreaseMalloc(); return NULL; } moveLeft = loadImage("../assets/sprites/moveLeft.png"); if (moveLeft != NULL) { worms->wormsSurfaceLeft = animationSprite(moveLeft, NULL, 15, 14); my_freeSurface(moveLeft); } moveRight = loadImage("../assets/sprites/moveRight.png"); if (moveRight != NULL) { worms->wormsSurfaceRight = animationSprite(moveRight, NULL, 15, 0); my_freeSurface(moveRight); } if (worms->wormsSurfaceLeft == NULL || worms->wormsSurfaceRight == NULL) { fprintf(logFile, "createWorms : FAILURE, createRGBSurface : %s.\n\n", SDL_GetError()); destroyWorms(&worms, 1); decreaseMalloc(); return NULL; } worms->wormsSurfaceTomb = loadImage("../assets/pictures/Tombe2_SD.png"); if (worms->wormsSurfaceTomb == NULL) { fprintf(logFile, "createWorms : FAILURE, loadImage.\n\n"); destroyWorms(&worms, 1); decreaseMalloc(); return NULL; } //initialisation des variables autres worms->vie = 100; sprintf(strVie, " %d ", worms->vie); worms->color = couleur; strcpy(worms->nom, name); worms->texteLifeSurface = my_RenderText_Blended(globalVar.FontName[0], strVie, *(worms->color)); worms->texteNameSurface = my_RenderText_Blended(globalVar.FontName[0], worms->nom, *(worms->color)); if (worms->texteLifeSurface == NULL || worms->texteNameSurface == NULL) { fprintf(logFile, "createWorms : FAILURE, texteSurface.\n\n"); destroyWorms(&worms, 1); return NULL; } //Initialisations liees a l'image du worms clip.x = 300; clip.y = 100; clip.w = worms->wormsSurfaceRight->w; clip.h = worms->wormsSurfaceRight->h; if ((worms->wormsObject = KaamInitObject(worms->wormsSurfaceRight, 0.0, 0.0, DOWN, 0)) == NULL) { fprintf(logFile, "createWorms : FAILURE, KaamInitObject.\n\n"); destroyWorms(&worms, 1); return NULL; } //worms->invent = initInvent(Worms* worms); A FAIRE worms->indexAnim = 0; worms->random = 0; worms->randomCounter = 0; worms->dirSurface = RIGHT; worms->arme = NULL; worms->team = team; worms->shotCounter = 0; //Enregistrement log fprintf(logFile, "\ncreateWorms : SUCCESS.\n\n"); return worms; }
int * af4() { int *p = my_malloc(12); my_free(p); return p; // expected-warning{{Use of memory after it is freed}} }
// This case is (possibly) ok, be conservative int * af5() { int *p = my_malloc(12); my_hold(p); return p; // no-warning }
// No leak if malloc returns null. void af2e() { int *p = my_malloc(12); if (!p) return; // no-warning free(p); // no-warning }
// This case inflicts a possible double-free. void af3() { int *p = my_malloc(12); my_hold(p); free(p); // expected-warning{{Attempt to free non-owned memory}} }
static ds_file_t * compress_open(ds_ctxt_t *ctxt, const char *path, MY_STAT *mystat) { ds_compress_ctxt_t *comp_ctxt; datasink_t *dest_ds; ds_ctxt_t *dest_ctxt; ds_file_t *dest_file; char new_name[FN_REFLEN]; size_t name_len; ds_file_t *file; ds_compress_file_t *comp_file; comp_ctxt = (ds_compress_ctxt_t *) ctxt->ptr; dest_ctxt = comp_ctxt->dest_ctxt; dest_ds = dest_ctxt->datasink; /* Append the .qp extension to the filename */ fn_format(new_name, path, "", ".qp", MYF(MY_APPEND_EXT)); dest_file = dest_ds->open(dest_ctxt, new_name, mystat); if (dest_file == NULL) { return NULL; } /* Write the qpress archive header */ if (dest_ds->write(dest_file, "qpress10", 8) || write_uint64_le(dest_ds, dest_file, COMPRESS_CHUNK_SIZE)) { goto err; } /* We are going to create a one-file "flat" (i.e. with no subdirectories) archive. So strip the directory part from the path and remove the '.qp' suffix. */ fn_format(new_name, path, "", "", MYF(MY_REPLACE_DIR)); /* Write the qpress file header */ name_len = strlen(new_name); if (dest_ds->write(dest_file, "F", 1) || write_uint32_le(dest_ds, dest_file, name_len) || /* we want to write the terminating \0 as well */ dest_ds->write(dest_file, new_name, name_len + 1)) { goto err; } file = (ds_file_t *) my_malloc(sizeof(ds_file_t) + sizeof(ds_compress_file_t), MYF(MY_FAE)); comp_file = (ds_compress_file_t *) (file + 1); comp_file->dest_file = dest_file; comp_file->dest_ds = dest_ds; comp_file->comp_ctxt = comp_ctxt; comp_file->bytes_processed = 0; file->ptr = comp_file; file->path = dest_file->path; return file; err: dest_ds->close(dest_file); return NULL; }
/** Get default action for a specified mimetype. */ static char *get_action( const char *mimetype ) { char *res=0; const char *launcher, *end; string_list_t mime_filenames; const char *launcher_str = NULL; const char *launcher_command_str, *launcher_command; char *launcher_full; if( !append_filenames( mime_filenames, DESKTOP_DEFAULT, 1 ) ) { return 0; } for ( size_t i = 0; i < mime_filenames.size(); i++ ) { launcher_str = search_ini( mime_filenames.at(i).c_str(), mimetype ); if ( launcher_str ) break; } if( !launcher_str ) { /* This type does not have a launcher. Try the supertype! */ // fprintf( stderr, "mimedb: %s does not have launcher, try supertype\n", mimetype ); const char ** parents = xdg_mime_get_mime_parents(mimetype); const char **p; if( parents ) { for( p=parents; *p; p++ ) { char *a = get_action(*p); if( a != 0 ) return a; } } /* Just in case subclassing doesn't work, (It doesn't on Fedora Core 3) we also test some common subclassings. */ if( strncmp( mimetype, "text/plain", 10) != 0 && strncmp( mimetype, "text/", 5 ) == 0 ) return get_action( "text/plain" ); return 0; } // fprintf( stderr, "WOOT %s\n", launcher_str ); launcher = const_cast<char*>(strchr( launcher_str, '=' )); if( !launcher ) { fprintf( stderr, _("%s: Could not parse launcher string '%s'\n"), MIMEDB, launcher_str ); error=1; return 0; } /* Skip the = */ launcher++; /* Make one we can change */ std::string mut_launcher = launcher; /* Only use first launcher */ end = strchr( launcher, ';' ); if( end ) mut_launcher.resize(end - launcher); launcher_full = (char *)my_malloc( mut_launcher.size() + strlen( APPLICATIONS_DIR)+1 ); if( !launcher_full ) { free( (void *)launcher_str ); return 0; } strcpy( launcher_full, APPLICATIONS_DIR ); strcat( launcher_full, mut_launcher.c_str() ); free( (void *)launcher_str ); std::string launcher_filename = get_filename( launcher_full ); free( launcher_full ); launcher_command_str = search_ini( launcher_filename.c_str(), "Exec" ); if( !launcher_command_str ) { fprintf( stderr, _( "%s: Default launcher '%s' does not specify how to start\n"), MIMEDB, launcher_filename.c_str() ); return 0; } launcher_command = strchr( launcher_command_str, '=' ); launcher_command++; res = my_strdup( launcher_command ); free( (void *)launcher_command_str ); return res; }
/** Get description for a specified mimetype. */ static char *get_description( const char *mimetype ) { char *fn_part; std::string fn; int fd; struct stat st; char *contents; char *start=0, *stop=0, *best_start=0; if( !start_re ) { char *lang; char buff[BUFF_SIZE]; lang = get_lang_re(); if( !lang ) return 0; snprintf( buff, BUFF_SIZE, START_TAG, lang, lang ); start_re = (regex_t *)my_malloc( sizeof(regex_t)); stop_re = (regex_t *)my_malloc( sizeof(regex_t)); int reg_status; if( ( reg_status = regcomp( start_re, buff, REG_EXTENDED ) ) ) { char regerrbuf[BUFF_SIZE]; regerror(reg_status, start_re, regerrbuf, BUFF_SIZE); fprintf( stderr, _( "%s: Could not compile regular expressions %s with error %s\n"), MIMEDB, buff, regerrbuf); error=1; } else if ( ( reg_status = regcomp( stop_re, STOP_TAG, REG_EXTENDED ) ) ) { char regerrbuf[BUFF_SIZE]; regerror(reg_status, stop_re, regerrbuf, BUFF_SIZE); fprintf( stderr, _( "%s: Could not compile regular expressions %s with error %s\n"), MIMEDB, buff, regerrbuf); error=1; } if( error ) { free( start_re ); free( stop_re ); start_re = stop_re = 0; return 0; } } fn_part = (char *)my_malloc( strlen(MIME_DIR) + strlen( mimetype) + strlen(MIME_SUFFIX) + 1 ); if( !fn_part ) { return 0; } strcpy( fn_part, MIME_DIR ); strcat( fn_part, mimetype ); strcat( fn_part, MIME_SUFFIX ); fn = get_filename(fn_part); //malloc( strlen(MIME_DIR) +strlen( MIME_SUFFIX)+ strlen( mimetype ) + 1 ); free(fn_part ); if( fn.empty() ) { return 0; } /* OK to not use CLO_EXEC here because mimedb is single threaded */ fd = open( fn.c_str(), O_RDONLY ); // fprintf( stderr, "%s\n", fn ); if( fd == -1 ) { perror( "open" ); error=1; return 0; } if( stat( fn.c_str(), &st) ) { perror( "stat" ); error=1; return 0; } contents = (char *)my_malloc( st.st_size + 1 ); if( !contents ) { return 0; } if( read( fd, contents, st.st_size ) != st.st_size ) { perror( "read" ); error=1; free((void *)contents); return 0; } /* Don't need to check exit status of close on read-only file descriptors */ close( fd ); contents[st.st_size]=0; regmatch_t match[1]; int w = -1; start=contents; /* On multiple matches, use the longest match, should be a pretty good heuristic for best match... */ while( !regexec(start_re, start, 1, match, 0) ) { int new_w = match[0].rm_eo - match[0].rm_so; start += match[0].rm_eo; if( new_w > w ) { /* New match is for a longer match then the previous match, so we use the new match */ w=new_w; best_start = start; } } if( w != -1 ) { start = best_start; if( !regexec(stop_re, start, 1, match, 0) ) { /* We've found the beginning and the end of a suitable description */ char *res; stop = start + match[0].rm_so; *stop = '\0'; res = munge( start ); free( contents ); return res; } } free( contents ); fprintf( stderr, _( "%s: No description for type %s\n"), MIMEDB, mimetype ); error=1; return 0; }
/* select training samples for part */ void select_examples_part(char *trainfile, SAMPLE sample, CAD *cad, int cad_index, int part_index) { int i, n, count, count_pos, count_neg; int *flag; float cx, cy; char line[BUFFLE_SIZE]; LABEL y; FILE *fp, *ftrain; n = sample.n; flag = (int*)my_malloc(sizeof(int)*n); memset(flag, 0, sizeof(int)*n); /* select positive samples */ count_pos = 0; for(i = 0; i < n; i++) { y = sample.examples[i].y; if(y.object_label == 1 && y.cad_label == cad_index) { cx = y.part_label[part_index]; cy = y.part_label[cad->part_num+part_index]; if(cad->objects2d[y.view_label]->occluded[part_index] == 0 && cx != 0 && cy != 0) { flag[i] = 1; count_pos++; } } } /* randomly select negative samples */ srand(time(NULL)); count_neg = 0; for(i = 0; i < n; i++) { y = sample.examples[i].y; if(y.object_label == -1 && rand()%2 == 0) { flag[i] = 1; count_neg++; if(count_neg >= count_pos) break; } } /* write samples */ printf("Writing data to temp_part.dat: %d positive samples, %d negative samples...\n", count_pos, count_neg); fp = fopen("temp_part.dat", "w"); ftrain = fopen(trainfile, "r"); if(ftrain == NULL) { printf("Cannot open file %s to read\n", trainfile); exit(1); } fscanf(ftrain, "%d\n", &n); fprintf(fp, "%d\n", count_pos+count_neg); count = 0; for(i = 0; i < n; i++) { fgets(line, BUFFLE_SIZE, ftrain); if(flag[i] == 1) { count++; fputs(line, fp); if(count >= count_pos + count_neg) break; } } fclose(fp); fclose(ftrain); printf("Done\n"); free(flag); }
void af1_b() { int *p = my_malloc(12); // expected-warning{{Memory is never released; potential leak}} }
/* select training samples for aspectlet */ void select_examples_aspectlet(char *trainfile, CAD **cads, int cad_index) { int i, j, n, count, count_pos, part_num, view_label; int *flag; char *pname; float azimuth, elevation, distance; FILE *fp; LABEL y; EXAMPLE example, *examples_aspectlet; /* find corresponding parts between two cads */ part_num = cads[cad_index]->part_num; flag = (int*)my_malloc(sizeof(int)*part_num); for(i = 0; i < part_num; i++) { pname = cads[cad_index]->part_names[i]; for(j = 0; j < cads[0]->part_num; j++) { if(strcmp(pname, cads[0]->part_names[j]) == 0) { flag[i] = j; break; } } } examples_aspectlet = NULL; /* select positive samples */ /* open data file */ if((fp = fopen(trainfile, "r")) == NULL) { printf("Can not open data file %s\n", trainfile); exit(1); } fscanf(fp, "%d", &n); count = 0; for(i = 0; i < n; i++) { /* read example */ example = read_one_example(fp, cads); y = example.y; if(y.object_label == 1) { azimuth = cads[0]->objects2d[y.view_label]->azimuth; elevation = cads[0]->objects2d[y.view_label]->elevation; distance = cads[0]->objects2d[y.view_label]->distance; /* find the view label */ view_label = -1; for(j = 0; j < cads[cad_index]->view_num; j++) { if(cads[cad_index]->objects2d[j]->azimuth == azimuth && cads[cad_index]->objects2d[j]->elevation == elevation && cads[cad_index]->objects2d[j]->distance == distance) { view_label = j; break; } } /* select the sample */ if(view_label != -1) { examples_aspectlet = (EXAMPLE*)realloc(examples_aspectlet, sizeof(EXAMPLE)*(count+1)); if(examples_aspectlet == NULL) { printf("out of memory\n"); exit(1); } /* construct the sample */ examples_aspectlet[count].y.object_label = y.object_label; examples_aspectlet[count].y.cad_label = y.cad_label; examples_aspectlet[count].y.view_label = view_label; examples_aspectlet[count].y.part_num = part_num; examples_aspectlet[count].y.part_label = (float*)my_malloc(sizeof(float)*2*part_num); /* get part labels */ for(j = 0; j < part_num; j++) { if(cads[cad_index]->roots[j] != -1) /* not root template */ { examples_aspectlet[count].y.part_label[j] = y.part_label[flag[j]]; examples_aspectlet[count].y.part_label[j+part_num] = y.part_label[flag[j]+cads[0]->part_num]; } else /* is root template */ { if(y.part_label[flag[j]] == 0 && y.part_label[flag[j]+cads[0]->part_num] == 0) /* root not visible */ { examples_aspectlet[count].y.part_label[j] = 0; examples_aspectlet[count].y.part_label[j+part_num] = 0; } else /* compute root location and bounding box */ compute_bbox_root(&(examples_aspectlet[count].y), j, cads[cad_index]); } } /* get occlusion label */ examples_aspectlet[count].y.occlusion = (int*)my_malloc(sizeof(int)*part_num); for(j = 0; j < part_num; j++) examples_aspectlet[count].y.occlusion[j] = y.occlusion[flag[j]]; examples_aspectlet[count].y.energy = 0; /* copy the image */ examples_aspectlet[count].x.image = copy_cumatrix(example.x.image); count++; } /* end if view_label != -1 */ free_pattern(example.x); free_label(example.y); } /* end if y.object_label == 1 */ else break; } /* select negative samples */ count_pos = count; for(; i < n; i++) { if(y.object_label == -1) { examples_aspectlet = (EXAMPLE*)realloc(examples_aspectlet, sizeof(EXAMPLE)*(count+1)); if(examples_aspectlet == NULL) { printf("out of memory\n"); exit(1); } examples_aspectlet[count].y.object_label = -1; examples_aspectlet[count].y.cad_label = -1; examples_aspectlet[count].y.view_label = -1; examples_aspectlet[count].y.part_num = -1; examples_aspectlet[count].y.part_label = NULL; examples_aspectlet[count].y.occlusion = NULL; for(j = 0; j < 4; j++) examples_aspectlet[count].y.bbox[j] = 0; examples_aspectlet[count].y.energy = 0; /* copy the image */ examples_aspectlet[count].x.image = copy_cumatrix(example.x.image); count++; if(count >= 2*count_pos) break; } free_pattern(example.x); free_label(example.y); example = read_one_example(fp, cads); y = example.y; } free_pattern(example.x); free_label(example.y); free(flag); fclose(fp); /* write examples */ printf("Writing data to temp_part.dat: %d positive samples, %d negative samples...\n", count_pos, count-count_pos); fp = fopen("temp_part.dat", "w"); fprintf(fp, "%d\n", count); for(i = 0; i < count; i++) { /* write object label */ fprintf(fp, "%d ", examples_aspectlet[i].y.object_label); if(examples_aspectlet[i].y.object_label == 1) { /* write cad label */ fprintf(fp, "%d ", examples_aspectlet[i].y.cad_label); /* write view label */ fprintf(fp, "%d ", examples_aspectlet[i].y.view_label); /* write part label */ for(j = 0; j < 2*part_num; j++) fprintf(fp, "%f ", examples_aspectlet[i].y.part_label[j]); /* write occlusion label */ for(j = 0; j < part_num; j++) fprintf(fp, "%d ", examples_aspectlet[i].y.occlusion[j]); /* write bounding box */ for(j = 0; j < 4; j++) fprintf(fp, "%f ", examples_aspectlet[i].y.bbox[j]); } /* write image size */ fprintf(fp, "%d ", examples_aspectlet[i].x.image.dims_num); for(j = 0; j < examples_aspectlet[i].x.image.dims_num; j++) fprintf(fp, "%d ", examples_aspectlet[i].x.image.dims[j]); /* write image pixel */ for(j = 0; j < examples_aspectlet[i].x.image.length; j++) fprintf(fp, "%u ", (unsigned int)examples_aspectlet[i].x.image.data[j]); fprintf(fp, "\n"); } fclose(fp); printf("Done\n"); /* clean up */ for(i = 0; i < count; i++) { free_pattern(examples_aspectlet[i].x); free_label(examples_aspectlet[i].y); } free(examples_aspectlet); }
void af1_c() { myglobalpointer = my_malloc(12); // no-warning }
/* Allocates the rr_indexed_data array and loads it with appropriate values. * * It currently stores the segment type (or OPEN if the index doesn't * * correspond to an CHANX or CHANY type), the base cost of nodes of that * * type, and some info to allow rapid estimates of time to get to a target * * to be computed by the router. * * * Right now all SOURCES have the same base cost; and similarly there's only * * one base cost for each of SINKs, OPINs, and IPINs (four total). This can * * be changed just by allocating more space in the array below and changing * * the cost_index values for these rr_nodes, if you want to make some pins * * etc. more expensive than others. I give each segment type in an * * x-channel its own cost_index, and each segment type in a y-channel its * * own cost_index. */ void alloc_and_load_rr_indexed_data(INP t_segment_inf * segment_inf, INP int num_segment, INP t_ivec *** L_rr_node_indices, INP int nodes_per_chan, int wire_to_ipin_switch, enum e_base_cost_type base_cost_type) { int iseg, length, i, index; num_rr_indexed_data = CHANX_COST_INDEX_START + (2 * num_segment); rr_indexed_data = (t_rr_indexed_data *) my_malloc( num_rr_indexed_data * sizeof(t_rr_indexed_data)); /* For rr_types that aren't CHANX or CHANY, base_cost is valid, but most * * * other fields are invalid. For IPINs, the T_linear field is also valid; * * * all other fields are invalid. For SOURCES, SINKs and OPINs, all fields * * * other than base_cost are invalid. Mark invalid fields as OPEN for safety. */ for (i = SOURCE_COST_INDEX; i <= IPIN_COST_INDEX; i++) { rr_indexed_data[i].ortho_cost_index = OPEN; rr_indexed_data[i].seg_index = OPEN; rr_indexed_data[i].inv_length = OPEN; rr_indexed_data[i].T_linear = OPEN; rr_indexed_data[i].T_quadratic = OPEN; rr_indexed_data[i].C_load = OPEN; } rr_indexed_data[IPIN_COST_INDEX].T_linear = switch_inf[wire_to_ipin_switch].Tdel; /* X-directed segments. */ for (iseg = 0; iseg < num_segment; iseg++) { index = CHANX_COST_INDEX_START + iseg; rr_indexed_data[index].ortho_cost_index = index + num_segment; if (segment_inf[iseg].longline) length = nx; else length = std::min(segment_inf[iseg].length, nx); rr_indexed_data[index].inv_length = 1. / length; rr_indexed_data[index].seg_index = iseg; } load_rr_indexed_data_T_values(CHANX_COST_INDEX_START, num_segment, CHANX, nodes_per_chan, L_rr_node_indices, segment_inf); /* Y-directed segments. */ for (iseg = 0; iseg < num_segment; iseg++) { index = CHANX_COST_INDEX_START + num_segment + iseg; rr_indexed_data[index].ortho_cost_index = index - num_segment; if (segment_inf[iseg].longline) length = ny; else length = std::min(segment_inf[iseg].length, ny); rr_indexed_data[index].inv_length = 1. / length; rr_indexed_data[index].seg_index = iseg; } load_rr_indexed_data_T_values((CHANX_COST_INDEX_START + num_segment), num_segment, CHANY, nodes_per_chan, L_rr_node_indices, segment_inf); load_rr_indexed_data_base_costs(nodes_per_chan, L_rr_node_indices, base_cost_type, wire_to_ipin_switch); }
void af1_d() { struct stuff mystuff; mystuff.somefield = my_malloc(12); // expected-warning{{Memory is never released; potential leak}} }
int SVMLightRunner::librarySVMLearnMain( int argc, char **argv, bool use_gmumr, SVMConfiguration &config ) { LOG( config.log, LogLevel::DEBUG_LEVEL, __debug_prefix__ + ".librarySVMLearnMain() Started." ); DOC **docs; /* training examples */ long totwords,totdoc,i; double *target; double *alpha_in=NULL; KERNEL_CACHE *kernel_cache; LEARN_PARM learn_parm; KERNEL_PARM kernel_parm; MODEL *model=(MODEL *)my_malloc(sizeof(MODEL)); // GMUM.R changes { librarySVMLearnReadInputParameters( argc, argv, docfile, modelfile, restartfile, &verbosity, &learn_parm, &kernel_parm, use_gmumr, config ); kernel_parm.kernel_type = static_cast<long int>(config.kernel_type); libraryReadDocuments( docfile, &docs, &target, &totwords, &totdoc, use_gmumr, config ); // GMUM.R changes } if(restartfile[0]) alpha_in=read_alphas(restartfile,totdoc); if(kernel_parm.kernel_type == LINEAR) { /* don't need the cache */ kernel_cache=NULL; } else { /* Always get a new kernel cache. It is not possible to use the * same cache for two different training runs */ kernel_cache=kernel_cache_init(totdoc,learn_parm.kernel_cache_size); } //gmum.r init_global_params_QP(); if(learn_parm.type == CLASSIFICATION) { svm_learn_classification(docs,target,totdoc,totwords,&learn_parm, &kernel_parm,kernel_cache,model,alpha_in); } else if(learn_parm.type == REGRESSION) { svm_learn_regression(docs,target,totdoc,totwords,&learn_parm, &kernel_parm,&kernel_cache,model); } else if(learn_parm.type == RANKING) { svm_learn_ranking(docs,target,totdoc,totwords,&learn_parm, &kernel_parm,&kernel_cache,model); } else if(learn_parm.type == OPTIMIZATION) { svm_learn_optimization(docs,target,totdoc,totwords,&learn_parm, &kernel_parm,kernel_cache,model,alpha_in); } //gmum.r config.iter = learn_parm.iterations; if(kernel_cache) { /* Free the memory used for the cache. */ kernel_cache_cleanup(kernel_cache); } /* Warning: The model contains references to the original data 'docs'. If you want to free the original data, and only keep the model, you have to make a deep copy of 'model'. */ /* deep_copy_of_model=copy_model(model); */ // GMUM.R changes { if (!use_gmumr) { write_model(modelfile,model); } else { SVMLightModelToSVMConfiguration(model, config); } // GMUM.R changes } free(alpha_in); free_model(model,0); for(i=0;i<totdoc;i++) free_example(docs[i],1); free(docs); free(target); LOG( config.log, LogLevel::DEBUG_LEVEL, __debug_prefix__ + ".librarySVMLearnMain() Done." ); return(0); }
// Test that we can pass out allocated memory via pointer-to-pointer. void af1_e(void **pp) { *pp = my_malloc(42); // no-warning }
MODEL * SVMLightRunner::libraryReadModel( char *modelfile, bool use_gmumr, SVMConfiguration &config ) { LOG( config.log, LogLevel::DEBUG_LEVEL, __debug_prefix__ + ".libraryReadModel() Started." ); FILE *modelfl; long i,queryid,slackid; double costfactor; long max_sv,max_words,ll,wpos; char *line,*comment; WORD *words; char version_buffer[100]; MODEL *model; if(verbosity>=1) { C_PRINTF("Reading model..."); C_FFLUSH(stdout); } // GMUM.R changes { model = (MODEL *)my_malloc(sizeof(MODEL)); if (!use_gmumr) { nol_ll(modelfile,&max_sv,&max_words,&ll); /* scan size of model file */ max_words+=2; ll+=2; words = (WORD *)my_malloc(sizeof(WORD)*(max_words+10)); line = (char *)my_malloc(sizeof(char)*ll); if ((modelfl = fopen (modelfile, "r")) == NULL) { perror (modelfile); EXIT (1); } fscanf(modelfl,"SVM-light Version %s\n",version_buffer); if(strcmp(version_buffer,VERSION)) { perror ("Version of model-file does not match version of svm_classify!"); EXIT (1); } fscanf(modelfl,"%ld%*[^\n]\n", &model->kernel_parm.kernel_type); fscanf(modelfl,"%ld%*[^\n]\n", &model->kernel_parm.poly_degree); fscanf(modelfl,"%lf%*[^\n]\n", &model->kernel_parm.rbf_gamma); fscanf(modelfl,"%lf%*[^\n]\n", &model->kernel_parm.coef_lin); fscanf(modelfl,"%lf%*[^\n]\n", &model->kernel_parm.coef_const); fscanf(modelfl,"%[^#]%*[^\n]\n", model->kernel_parm.custom); fscanf(modelfl,"%ld%*[^\n]\n", &model->totwords); fscanf(modelfl,"%ld%*[^\n]\n", &model->totdoc); fscanf(modelfl,"%ld%*[^\n]\n", &model->sv_num); fscanf(modelfl,"%lf%*[^\n]\n", &model->b); } else { // use_gmumr max_words = config.getDataDim(); words = (WORD *)my_malloc(sizeof(WORD)*(max_words+10)); LOG( config.log, LogLevel::DEBUG_LEVEL, __debug_prefix__ + ".libraryReadModel() Converting config to model..." ); /* 0=linear, 1=poly, 2=rbf, 3=sigmoid, 4=custom -- same as GMUM.R! */ model->kernel_parm.kernel_type = static_cast<long int>(config.kernel_type); // -d int -> parameter d in polynomial kernel model->kernel_parm.poly_degree = config.degree; // -g float -> parameter gamma in rbf kernel model->kernel_parm.rbf_gamma = config.gamma; // -s float -> parameter s in sigmoid/poly kernel model->kernel_parm.coef_lin = config.gamma; // -r float -> parameter c in sigmoid/poly kernel model->kernel_parm.coef_const = config.coef0; // -u string -> parameter of user defined kernel char kernel_parm_custom[50] = "empty"; char * model_kernel_parm_custom = model->kernel_parm.custom; model_kernel_parm_custom = kernel_parm_custom; // highest feature index model->totwords = config.getDataDim(); // number of training documents model->totdoc = config.target.n_rows; // number of support vectors plus 1 (!) model->sv_num = config.l + 1; /* Threshold b (has opposite sign than SVMClient::predict()) * In svm_common.c:57 in double classify_example_linear(): * return(sum-model->b); */ model->b = - config.b; LOG( config.log, LogLevel::DEBUG_LEVEL, __debug_prefix__ + ".libraryReadModel() Converting config done." ); } // GMUM.R changes } model->supvec = (DOC **)my_malloc(sizeof(DOC *)*model->sv_num); model->alpha = (double *)my_malloc(sizeof(double)*model->sv_num); model->index=NULL; model->lin_weights=NULL; // GMUM.R changes { if (!use_gmumr) { for(i=1;i<model->sv_num;i++) { fgets(line,(int)ll,modelfl); if(!parse_document(line,words,&(model->alpha[i]),&queryid,&slackid, &costfactor,&wpos,max_words,&comment)) { C_PRINTF("\nParsing error while reading model file in SV %ld!\n%s", i,line); EXIT(1); } model->supvec[i] = create_example(-1, 0,0, 0.0, create_svector(words,comment,1.0)); } fclose(modelfl); free(line); } else { for(i = 1; i < model->sv_num; ++i) { line = SVMConfigurationToSVMLightModelSVLine(config, i-1); if(!parse_document(line,words,&(model->alpha[i]),&queryid,&slackid, &costfactor,&wpos,max_words,&comment)) { C_PRINTF("\nParsing error while reading model file in SV %ld!\n%s", i,line); EXIT(1); } model->supvec[i] = create_example(-1, 0,0, 0.0, create_svector(words,comment,1.0)); free(line); } } // GMUM.R changes } free(words); if(verbosity>=1) { C_FPRINTF(stdout, "OK. (%d support vectors read)\n",(int)(model->sv_num-1)); } LOG( config.log, LogLevel::DEBUG_LEVEL, __debug_prefix__ + ".libraryReadModel() Done." ); return(model); }
void af1_f(struct stuff *somestuff) { somestuff->somefield = my_malloc(12); // no-warning }
long PackCheckBFS(const char * FileName, PUCHAR BaseString, long readed, long &HeadOffset, long &SomeOffset, long &FileSize, long &FileOffset, struct RIP_FILE_INFO **finfo, long &FilesNumber, long WorkFileSize, struct RIP_SERVICE_FUNC *func, struct RIP_FLAGS *flags) { char DirName[MAX_PATH]; #pragma pack(1) struct { long Type; long Offset; long RealSize; long PackedSize; long Data; short NameLen; }DatInfo; #pragma pack(8) unsigned char t[] = {'b','f','s','1',0x05,0x05,0x04,0x20}; long rd, SOffset, FOffset, TOffset, DirLen, filestotal; RIP_FILE_INFO * fi; long fres = func->Find(t, BaseString, sizeof t, readed); if (fres == -1) return -1; SOffset = FileOffset+fres; FOffset = SOffset+8; rd = func->ReadFromFile(FileName, FOffset, &DirLen, sizeof DirLen); if (rd < sizeof DirLen) return -1; FileSize = DirLen+1; if (DirLen >= WorkFileSize) return -1; FOffset += rd; rd = func->ReadFromFile(FileName, FOffset, &filestotal, 4); if (rd < 4) return -1; FOffset += rd; fi = (RIP_FILE_INFO*)my_malloc(sizeof(RIP_FILE_INFO)*filestotal); if (fi == NULL) return -1; *finfo = fi; FilesNumber = filestotal; for (int i = 0; i<FilesNumber; i++){ rd = func->ReadFromFile(FileName, FOffset, &TOffset, 4); if (rd < 4) return -1; FOffset += rd; //Read FAT record rd = func->ReadFromFile(FileName, TOffset, &DatInfo, sizeof DatInfo); if (rd < sizeof DatInfo) return -1; TOffset += rd; rd = func->ReadFromFile(FileName, TOffset, &DirName, DatInfo.NameLen); if (rd < DatInfo.NameLen) return -1; DirName[DatInfo.NameLen] = 0; memset(&fi[i], 0, sizeof(RIP_FILE_INFO)); fi[i].StartOffset = DatInfo.Offset; fi[i].FileSize = DatInfo.PackedSize; fi[i].UnpSize = DatInfo.RealSize; /* fi[i].UserData = (long*)my_malloc(sizeof(long)); memcpy(fi[i].UserData, &DatInfo.Type, sizeof DatInfo.Type); fi[i].UserDataLen = sizeof DatInfo.Type;*/ FileSize += DatInfo.PackedSize; if (fi[i].StartOffset+fi[i].FileSize>WorkFileSize){ for (int j=0; j<i; j++) { my_free(fi[j].FullFileName); my_free(fi[j].Description); } my_free(fi); return -1; } fi[i].FullFileName = (char*)my_malloc(strlen(DirName)+1); strcpy(fi[i].FullFileName, DirName); fi[i].Description = (char*)my_malloc(strlen("")+1); strcpy(fi[i].Description, ""); } FileOffset = SOffset; return WorkFileSize; }
// Allocating memory for a field via multiple indirections to our arguments is OK. void af1_g(struct stuff **pps) { *pps = my_malloc(sizeof(struct stuff)); // no-warning (*pps)->somefield = my_malloc(42); // no-warning }
MY_DIR *my_dir(const char *path, myf MyFlags) { DIR *dirp; struct dirent *dp; struct fileinfo *fnames; char *buffer, *obuffer, *tempptr; uint fcnt,i,size,firstfcnt, maxfcnt,length; char tmp_path[FN_REFLEN+1],*tmp_file; my_ptrdiff_t diff; bool eof; #ifdef THREAD char dirent_tmp[sizeof(struct dirent)+_POSIX_PATH_MAX+1]; #endif DBUG_ENTER("my_dir"); DBUG_PRINT("my",("path: '%s' stat: %d MyFlags: %d",path,MyFlags)); #if defined(THREAD) && !defined(HAVE_READDIR_R) pthread_mutex_lock(&THR_LOCK_open); #endif dirp = opendir(directory_file_name(tmp_path,(my_string) path)); size = STARTSIZE; if (dirp == NULL || ! (buffer = (char *) my_malloc(size, MyFlags))) goto error; fcnt = 0; tmp_file=strend(tmp_path); firstfcnt = maxfcnt = (size - sizeof(MY_DIR)) / (sizeof(struct fileinfo) + FN_LEN); fnames= (struct fileinfo *) (buffer + sizeof(MY_DIR)); tempptr = (char *) (fnames + maxfcnt); #ifdef THREAD dp= (struct dirent*) dirent_tmp; #else dp=0; #endif eof=0; for (;;) { while (fcnt < maxfcnt && !(eof= READDIR(dirp,(struct dirent*) dirent_tmp,dp))) { bzero((gptr) (fnames+fcnt),sizeof(fnames[0])); /* for purify */ fnames[fcnt].name = tempptr; tempptr = strmov(tempptr,dp->d_name) + 1; if (MyFlags & MY_WANT_STAT) { VOID(strmov(tmp_file,dp->d_name)); VOID(my_stat(tmp_path, &fnames[fcnt].mystat, MyFlags)); } ++fcnt; } if (eof) break; size += STARTSIZE; obuffer = buffer; if (!(buffer = (char *) my_realloc((gptr) buffer, size, MyFlags | MY_FREE_ON_ERROR))) goto error; /* No memory */ length= (uint) (sizeof(struct fileinfo ) * firstfcnt); diff= PTR_BYTE_DIFF(buffer , obuffer) + (int) length; fnames= (struct fileinfo *) (buffer + sizeof(MY_DIR)); tempptr= ADD_TO_PTR(tempptr,diff,char*); for (i = 0; i < maxfcnt; i++) fnames[i].name = ADD_TO_PTR(fnames[i].name,diff,char*); /* move filenames upp a bit */ maxfcnt += firstfcnt; bmove_upp(tempptr,tempptr-length, (uint) (tempptr- (char*) (fnames+maxfcnt))); } (void) closedir(dirp); { MY_DIR * s = (MY_DIR *) buffer; s->number_off_files = (uint) fcnt; s->dir_entry = fnames; } if (!(MyFlags & MY_DONT_SORT)) qsort((void *) fnames, (size_s) fcnt, sizeof(struct fileinfo), (qsort_cmp) comp_names); #if defined(THREAD) && !defined(HAVE_READDIR_R) pthread_mutex_unlock(&THR_LOCK_open); #endif DBUG_RETURN((MY_DIR *) buffer); error: #if defined(THREAD) && !defined(HAVE_READDIR_R) pthread_mutex_unlock(&THR_LOCK_open); #endif my_errno=errno; if (dirp) (void) closedir(dirp); if (MyFlags & (MY_FAE+MY_WME)) my_error(EE_DIR,MYF(ME_BELL+ME_WAITTANG),path,my_errno); DBUG_RETURN((MY_DIR *) NULL); } /* my_dir */
void af2b() { int *p = my_malloc(12); free(p); my_free(p); // expected-warning{{Attempt to free released memory}} }
int main(int argc, char** argv) { char* server_key = 0, *server_cert = 0; char* client_key = 0, *client_cert = 0; char* ca_file = 0, *ca_path = 0; char* cipher=0; int child_pid,sv[2]; my_bool unused; struct st_VioSSLFd* ssl_acceptor= 0; struct st_VioSSLFd* ssl_connector= 0; Vio* client_vio=0, *server_vio=0; enum enum_ssl_init_error ssl_init_error; unsigned long ssl_error; MY_INIT(argv[0]); DBUG_PROCESS(argv[0]); DBUG_PUSH(default_dbug_option); if (argc<5) { print_usage(); return 1; } server_key = argv[1]; server_cert = argv[2]; client_key = argv[3]; client_cert = argv[4]; if (argc>5) ca_file = argv[5]; if (argc>6) ca_path = argv[6]; printf("Server key/cert : %s/%s\n", server_key, server_cert); printf("Client key/cert : %s/%s\n", client_key, client_cert); if (ca_file!=0) printf("CAfile : %s\n", ca_file); if (ca_path!=0) printf("CApath : %s\n", ca_path); if (socketpair(PF_UNIX, SOCK_STREAM, IPPROTO_IP, sv)==-1) fatal_error("socketpair"); ssl_acceptor = new_VioSSLAcceptorFd(server_key, server_cert, ca_file, ca_path, cipher); ssl_connector = new_VioSSLConnectorFd(client_key, client_cert, ca_file, ca_path, cipher, &ssl_init_error); client_vio = (struct st_vio*)my_malloc(sizeof(struct st_vio),MYF(0)); client_vio->sd = sv[0]; client_vio->vioblocking(client_vio, 0, &unused); sslconnect(ssl_connector,client_vio,60L,&ssl_error); server_vio = (struct st_vio*)my_malloc(sizeof(struct st_vio),MYF(0)); server_vio->sd = sv[1]; server_vio->vioblocking(client_vio, 0, &unused); sslaccept(ssl_acceptor,server_vio,60L, &ssl_error); printf("Socketpair: %d , %d\n", client_vio->sd, server_vio->sd); child_pid = fork(); if (child_pid==-1) { my_free(ssl_acceptor); my_free(ssl_connector); fatal_error("fork"); } if (child_pid==0) { /* child, therefore, client */ char xbuf[100]; int r = vio_read(client_vio,xbuf, sizeof(xbuf)); if (r<=0) { my_free(ssl_acceptor); my_free(ssl_connector); fatal_error("client:SSL_read"); } xbuf[r] = 0; printf("client:got %s\n", xbuf); my_free(client_vio); my_free(ssl_acceptor); my_free(ssl_connector); } else { const char* s = "Huhuhuh"; int r = vio_write(server_vio,(uchar*)s, strlen(s)); if (r<=0) { my_free(ssl_acceptor); my_free(ssl_connector); fatal_error("server:SSL_write"); } my_free(server_vio); my_free(ssl_acceptor); my_free(ssl_connector); } return 0; }
int main() { FILE * pFile; pFile = fopen ("test1_output.txt","w"); int size; int RAM_SIZE=1<<20; /* 1024*1024 */ void* RAM=malloc(RAM_SIZE); /* 1024*1024 */ setup(0,RAM_SIZE,RAM); /* First Fit, Memory size=1024*1024, Start of memory=RAM */ /* test 1 */ size=20*1024; void* a=my_malloc(size); /* We have 4 bytes header to save the size of that chunk in memory so the output starts at 4 */ if ((int)a==-1) fprintf(pFile, "This size can not be allocated!"); else { fprintf(pFile, "start of the chunk a: %d\n",(int)(a-RAM)); fprintf(pFile, "End of the chunk a: %d\n\n",(int)(a+size-RAM)); } size=30*1024; void* b=my_malloc(size); if ((int)b==-1) fprintf(pFile, "This size can not be allocated!"); else { fprintf(pFile, "start of the chunk b: %d\n",(int)(b-RAM)); fprintf(pFile, "End of the chunk b: %d\n\n",(int)(b+size-RAM)); } size=15*1024; void* c=my_malloc(size); if ((int)c==-1) fprintf(pFile, "This size can not be allocated!"); else { fprintf(pFile, "start of the chunk c: %d\n",(int)(c-RAM)); fprintf(pFile, "End of the chunk c: %d\n\n",(int)(c+size-RAM)); } size=25*1024; void* d=my_malloc(size); if ((int)d==-1) fprintf(pFile, "This size can not be allocated!"); else { fprintf(pFile, "start of the chunk d: %d\n",(int)(d-RAM)); fprintf(pFile, "End of the chunk d: %d\n\n",(int)(d+size-RAM)); } size=35*1024; void* e=my_malloc(size); if ((int)e==-1) fprintf(pFile, "This size can not be allocated!"); else { fprintf(pFile, "start of the chunk e: %d\n",(int)(e-RAM)); fprintf(pFile, "End of the chunk e: %d\n\n",(int)(e+size-RAM)); } size=35*1024; void* f=my_malloc(size); if ((int)f==-1) fprintf(pFile, "This size can not be allocated!"); else { fprintf(pFile, "start of the chunk f: %d\n",(int)(f-RAM)); fprintf(pFile, "End of the chunk f: %d\n\n",(int)(f+size-RAM)); } size=25*1024; void* g=my_malloc(size); if ((int)g==-1) fprintf(pFile, "This size can not be allocated!"); else { fprintf(pFile, "start of the chunk g: %d\n",(int)(g-RAM)); fprintf(pFile, "End of the chunk g: %d\n\n",(int)(g+size-RAM)); } my_free(b); my_free(d); my_free(f); size=25*1024; void* h=my_malloc(size); if ((int)h==-1) fprintf(pFile, "This size can not be allocated!"); else { fprintf(pFile, "start of the chunk h: %d\n",(int)(h-RAM)); fprintf(pFile, "End of the chunk h: %d\n\n",(int)(h+size-RAM)); } fclose (pFile); return 0; }