Segfault on fscanf - c

filenamelists is a struct with two file pointers. merge mergesorts these two fileptrs. I'm getting a segfault on the while(fscanf(filenamelist[0].file1, "%d", &chd) != EOF). I think its because I'm not implementing pthread correctly. Ive been trying to debug forever so any help would be appreciated. tempf is a file ptr to the mergesorted arrays. It is rewinded in the merge function itself.
for(i=0; i<size; i++)
{
if(argc==1)
{
char* tedious2 = (char*) malloc((strlen(argv[i+1]+7))*sizeof(char));
strcpy(tedious2,argv[i+1]);
filenamelist[i].file1 = fopen(strcat(tedious2,".sorted"),"r");
filenamelist[i].file2 = NULL;
filenamelist[i].alone = 1;
free(tedious2);
break;
}
else if(size-1 ==i && size%2 != 0)
{
char* tedious1 = (char*) malloc((strlen(argv[i+1]+7))*sizeof(char));
strcpy(tedious1,argv[i+1]);
filenamelist[i].file1 = fopen(strcat(tedious1,".sorted"),"r");
filenamelist[i].file2 = NULL;
filenamelist[i].alone = 1;
free(tedious1);
}
else
{
char* tedious3 = (char*) malloc((strlen(argv[i+1]+7))*sizeof(char));
strcpy(tedious3,argv[i+1]);
char* tedious4 = (char*) malloc((strlen(argv[i+2]+7))*sizeof(char));
strcpy(tedious4,argv[i+2]);
filenamelist[i].file1 = fopen(strcat(tedious3,".sorted"),"r");
filenamelist[i].file2 = fopen(strcat(tedious4,".sorted"),"r");
filenamelist[i].alone = 0;
free(tedious3);
free(tedious4);
}
}
// pthread_t* threadid2;
// threadid2 = (pthread_t*) malloc(sizeof(pthread_t)*(2*argc));
while(size>=0)
{
i = 0;
pthread_t* threadid2;
threadid2 = (pthread_t*) malloc(sizeof(pthread_t)*size);
for ( ; i<size;i++ )
{
pthread_create(&threadid2[i], NULL, merge, &filenamelist[i]);
}
i = 0;
for ( ; i<size; i++)
{
pthread_join(threadid2[i], tempf);
if (i%2 == 0)
{
filenamelist[i/2].file1 = tempf;
}
else
{
filenamelist[i/2].file2 = tempf;
}
}
zit=0;
truth = 0;
while(zit<z)
{
if(inputFiles[zit] == tempf)
truth = 1;
zit++;
}
if(truth != 1)
{
inputFiles[z] = tempf;
z++;
}
if(size==1)
size = 0;
else if (size % 2 == 0)
size = size/2;
else
size = (size/2)+1;
free(threadid2);
}
int chd = 0;
// if(0!=feof(tempf))
// rewind(tempf);
//rewind(filenamelist[0]->file1);
int finish = 0;
//printf("file 1:%p",tempf);
while(fscanf(filenamelist[0].file1, "%d", &chd) != EOF)
finish++;
rewind(filenamelist[0].file1);
int* finarr = (int*) malloc(finish*sizeof(int));
int xx =0;
for(;fscanf(filenamelist[0].file1, "%d", &chd) != EOF; xx++)
finarr[xx] = chd;
tempf is declared at start of func as FILE* tempf;

char* tedious2 = (char*) malloc((strlen(argv[i+1]+7))*sizeof(char));
Make that:
char *tedious2 = malloc( strlen(argv[i+1]) + strlen(".sorted") + 1 );

Related

C program can't figure out how to properly free mallocs

In the main function of my program I make a few malloc calls and what I think are the right free calls at the end. My address sanitizer is telling me that data is still leaking in line 206, which is:
names[size - 1] = malloc(17 * sizeof(char));
The problem is that if I include a free statement for names[size - 1], there is apparently data still leaking from it. I have no idea why. Here is the main:
int main(int argc, char** argv) {
if (argc - 1 != 1) {
printf("Invalid number of arguments\n");
return 0;
}
//get file, return if invalid path
FILE *file = fopen(argv[1], "r");
if (!file) {
printf("Invalid input\n");
return 0;
}
//make temp of circuit with struct directive
int scount = 0;
struct directive* temp = NULL;
int size = 2;
int icount = 0;
int ocount = 0;
int tcount = 0;
char dir[17];
char **names;
int *values;
//get INPUT info
fscanf(file, " %s", dir);
fscanf(file, "%d", &icount);
size += icount;
names = malloc(size * sizeof(char *));
names[0] = malloc(2 * sizeof(char)); //MALLOC
strcpy(names[0], "0");
names[1] = malloc(2 * sizeof(char)); //MALLOC
strcpy(names[1], "1");
int i;
for (i = 0; i < icount; i++) {
names[i + 2] = malloc(17 * sizeof(char));
fscanf(file, "%*[: ]%16s", names[i + 2]);
}
//get OUTPUT info
fscanf(file, " %s", dir);
fscanf(file, "%d", &ocount);
size += ocount;
names = realloc(names, size * sizeof(char *));
for (i = 0; i < ocount; i++) {
names[i + icount + 2] = malloc(17 * sizeof(char));
fscanf(file, "%*[: ]%16s", names[i + icount + 2]);
}
//get temp
struct directive step;
while (!feof(file)) {
int numInputs = 2, numOutputs = 1;
int sc = fscanf(file, " %s", dir);
if (sc != 1) {
break;
}
scount++;
step.n = 0;
step.s = 0;
strcpy(step.gate, dir);
if (strcmp(dir, "NOT") == 0) {
numInputs = 1;
}
if (strcmp(dir, "PASS") == 0) {
numInputs = 1;
}
if (strcmp(dir, "DECODER") == 0) {
fscanf(file, "%d", &numInputs);
step.n = numInputs;
numOutputs = pow(2, numInputs);
}
if (strcmp(dir, "MULTIPLEXER") == 0) {
fscanf(file, "%d", &numInputs);
step.s = numInputs;
numInputs = pow(2, numInputs);
}
step.inputs = malloc(numInputs * sizeof(int));
step.outputs = malloc(numOutputs * sizeof(int));
step.selectors = malloc(step.s * sizeof(int));
char v[17];
for (i = 0; i < numInputs; i++) {
fscanf(file, "%*[: ]%16s", v);
step.inputs[i] = indexOf(size, names, v);
}
for (i = 0; i < step.s; i++) {
fscanf(file, "%*[: ]%16s", v);
step.selectors[i] = indexOf(size, names, v);
}
for (i = 0; i < numOutputs; i++) {
fscanf(file, "%*[: ]%16s", v);
int idx = indexOf(size, names, v);
if (idx == -1) {
size++;
tcount++;
char **tmp = realloc(names, size * sizeof *tmp);
if (!tmp) abort(); // handle alloc failure
names = tmp;
names[size - 1] = malloc(17 * sizeof(char));
strcpy(names[size - 1], v);
step.outputs[i] = size - 1;
}
else {
step.outputs[i] = idx;
}
}
//add step to list of temp
if (!temp) {
temp = malloc(sizeof(struct directive));
} else {
temp = realloc(temp, scount * sizeof(struct directive));
}
temp[scount - 1] = step;
}
// initialize values array
values = malloc(size * sizeof(int));
resetValues(size, values);
while(1 < 2) {
//print inputs
for (i = 0; i < icount; i++) {
printf("%d ", values[i + 2]);
}
printf("|");
//run through temp, calculate outputs
for (i = 0; i < scount; i++) {
struct directive step = temp[i];
if (strcmp(step.gate, "NOT") == 0) {
NOT(values, step.inputs[0], step.outputs[0]);
}
if (strcmp(step.gate, "AND") == 0) {
AND(values, step.inputs[0], step.inputs[1], step.outputs[0]);
}
if (strcmp(step.gate, "OR") == 0) {
OR(values, step.inputs[0], step.inputs[1], step.outputs[0]);
}
if (strcmp(step.gate, "NAND") == 0) {
NAND(values, step.inputs[0], step.inputs[1], step.outputs[0]);
}
if (strcmp(step.gate, "NOR") == 0) {
NOR(values, step.inputs[0], step.inputs[1], step.outputs[0]);
}
if (strcmp(step.gate, "XOR") == 0) {
XOR(values, step.inputs[0], step.inputs[1], step.outputs[0]);
}
if (strcmp(step.gate, "PASS") == 0) {
PASS(values, step.inputs[0], step.outputs[0]);
}
if (strcmp(step.gate, "DECODER") == 0) {
DECODER(values, step.n, step.inputs, step.outputs);
}
if (strcmp(step.gate, "MULTIPLEXER") == 0) {
MUX(values, step.s, step.inputs, step.selectors, step.outputs[0]);
}
}
//print outputs
for (i = 0; i < ocount; i++) {
printf(" %d", values[icount + i + 2]);
}
printf("\n");
if (!incrementInputs(values, icount)) {
break;
}
}
for (i = 0; i < icount; i++) {
free(names[i + 2]);
}
for (i = 0; i < ocount; i++) {
free(names[i + icount + 2]);
}
for (int i = 0; i < scount; i++) {
free(temp[i].inputs);
free(temp[i].outputs);
free(temp[i].selectors);
}
free(names[0]);
free(names[1]);
//free(names[size-1]);
free(values);
free(temp);
free(names);
return 0;
}

Breakpoint on Malloc char ***a

I have a project to finish ...... and for this i need a char ***a to get all the words that reffer to the dictionary names from a text file (for a translator).
My program always breakpoints on the strcpy(a[line][v[i]], p); I'm stuck numar_cuvinte = word_number linie = line
while (!feof(dictionary_list))
{
fgets(buffer, 100, dictionary_list);
p = strtok(buffer, "-.\n");
while (p != NULL)
{
if (p != "txt")
{
nr_cuvinte++;
p = strtok(NULL, "-.\n");
}
else
p = NULL;
}
v[linie] = nr_cuvinte; // ---------> v[i] = nr cuvinte pe linie
nr_cuvinte = 0;// ----->m
linie++; // --->n
}
//-------------------------------------------------------------------------
a = (char***)malloc(linie*sizeof(char**));
for (int i = 0; i < linie; i++)
{
a[i] = (char**)malloc(v[i] * sizeof(char*));
}
for (int i = 0; i < linie; i++)
{
for (int j = 0; j < v[i]; j++)
{
a[i][j] = (char*)malloc(20 * sizeof(char));
}
}
//--------------------------------------------------------------------------
rewind(dictionary_list);
linie = 0;
nr_cuvinte = 0;
while (!feof(dictionary_list))
{
fgets(buffer, 100, dictionary_list);
p = strtok(buffer, "-.\n");
while (p != NULL)
{
if (p != "txt")
{
strcpy(a[linie][v[nr_cuvinte]], p);
nr_cuvinte++;
p = strtok(NULL, "-.\n");
}
else p = NULL;
}
v[linie] = nr_cuvinte;
nr_cuvinte = 0;// ----->m
linie++; // --->n
}
}

C malloc segmentation fault

In the function RenameSubs() when I try debugging I get segmentation fault at this line of code
subsdir[i] = (char*)malloc((GetStringSize(moviesdir[i]) + 1 + 4) * sizeof(char));
I don't understand why — can you explain?
int main()
{
int number;
char *mainDirectory = NULL,**names = NULL;
printf("Give the movies directory: ");
mainDirectory = ReadMainDirectory();
if(GetFiles(&mainDirectory,&names,&number) != 0)
{
RenameSubs(number,mainDirectory,names);
system("PAUSE");
return 1;
}
system("PAUSE");
return 0;
}
char* ReadMainDirectory()
{
char *dir,c;
int size = 1;
dir = (char*)malloc(size+1);
dir[size-1] = '\0';
while((c = getchar()) != '\n')
{
dir[size-1] = c;
size++;
dir = (char*)realloc(dir,size+1);
dir[size-1] = '\0';
}
return dir;
}
int GetFiles(char **dir,char ***names,int *number)
{
struct dirent *dp;
DIR *fd;
if ((fd = opendir(*dir)) == NULL)
{
printf("Can't open directory %s!\n",*dir);
return 0;
}
*number = 0;
*names = (char**)malloc(((*number)+1) * sizeof(char*));
while ((dp = readdir(fd)) != NULL)
{
if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
{
continue;
}
(*names)[*number] = strdup(dp->d_name);
(*number)++;
*names = (char**)realloc(*names,((*number)+1) * sizeof(char*));
}
closedir(fd);
return 1;
}
int GetStringSize(char *string)
{
int size = 0;
while(string[size] != '\0')
{
size++;
}
return size;
}
int StringEndsWith(char* string,char* extension)
{
int size;
char *strextension = NULL;
size = GetStringSize(string);
strextension = (char*)malloc(5 * sizeof(char));
strextension[0] = string[size-4];
strextension[1] = string[size-3];
strextension[2] = string[size-2];
strextension[3] = string[size-1];
strextension[4] = '\0';
if(strcmp(strextension,extension) == 0)
{
return 1;
}
return 0;
}
void RenameSubs(int number,char* mainDir,char** filenames)
{
int i,mainDirSize,movieDirSize[number],moviesdirnumber,subsdirnumber,j,y;
char **moviesdir = NULL,**subsdir = NULL,**subsdest = NULL,**moviesdirfilenames = NULL,**subsdirfilenames = NULL,*moviesname = NULL;
moviesdir = (char**)malloc(number * sizeof(char*));
mainDirSize = GetStringSize(mainDir);
for(i=0;i<number;i++)
{
movieDirSize[i] = mainDirSize + 1 + GetStringSize(filenames[i]);
moviesdir[i] = (char*)malloc((movieDirSize[i]+1) * sizeof(char));
strcpy(moviesdir[i],mainDir);
strcat(moviesdir[i],"\\");
strcat(moviesdir[i],filenames[i]);
GetFiles(&moviesdir[i],&moviesdirfilenames,&moviesdirnumber);
subsdir[i] = (char*)malloc((GetStringSize(moviesdir[i]) + 1 + 4) * sizeof(char));
strcpy(subsdir[i],moviesdir[i]);
strcat(subsdir[i],"\\");
strcat(subsdir[i],"Subs");
GetFiles(&subsdir[i],&subsdirfilenames,&subsdirnumber);
subsdest[i] = (char*)malloc((GetStringSize(subsdir[i]) + GetStringSize(subsdirfilenames[0]) + 1) * sizeof(char));
strcpy(subsdest[i],subsdir[i]);
strcat(subsdest[i],"\\");
strcat(subsdest[i],subsdirfilenames[0]);
for(j=0;j<moviesdirnumber;j++)
{
if(StringEndsWith(moviesdirfilenames[j],".mkv") || StringEndsWith(moviesdirfilenames[j],".mp4") || StringEndsWith(moviesdirfilenames[j],".avi"))
{
moviesname = (char*)malloc((GetStringSize(moviesdirfilenames[j]) - 4 + 1) * sizeof(char));
for(y=0;y<(GetStringSize(moviesdirfilenames[j]) - 4);y++)
{
moviesname[y] = moviesdirfilenames[j][y];
}
moviesname[y] = '\0';
break;
}
}
}
}
You are using array of pointers without initializing it first . initialize it.
In loop
subsdir[i] = malloc((GetStringSize(moviesdir[i]) + 1 + 4) * sizeof(char));
This is the second step . First u need to initialize
subsdir = malloc (sizeof(char*) * number);

C int pointer allocation size [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
its a very very anoing problem what i get. My problem is, gcc seems not allocate enough space to my int pointer.
Here is the code:
fns = (int*)calloc(c,sizeof(int));
So, after then i fill up this in a simple loop ones and zeros:
offset = seekToFirstParam(fnString,n);
i = 0;
while(i<c) {
tmp[i] = readNextParam(fnString,n,offset,&s);
if (isFunctionString(tmp[i])) {
fns[i] = 1;
} else {
fns[i] = 0;
}
i++;
}
So this is a "flag" array, but when i debug this, and print the elements i get:
156212102, 0, 0, 0, 1, 1
Or som. like this. I don't get it, because if in the calloc method i write 1000 like this:
fns = (int*)calloc(1000,sizeof(int));
After works fine.
Ok, this is a hole function:
char **readFnParams(char *fnString, int n, int *count, int **func) {
char **tmp;
int *fns = NULL;
int c,i = 0,offset,s;
c = getParamsCount(fnString,n);
if (!c) {
return NULL;
}
tmp = (char**)calloc(c,sizeof(char));
fns = (int*)calloc(c,sizeof(int*));
offset = seekToFirstParam(fnString,n);
while(i<c) {
tmp[i] = readNextParam(fnString,n,offset,&s);
if (isFunctionString(tmp[i])) {
tmp[i] = readNextFunctionParam(fnString,n,offset,&s);
offset = seekToNextParam(fnString,n,offset + s - 1);
fns[i] = 1;
} else {
fns[i] = 0;
offset = seekToNextParam(fnString,n,offset);
}
i++;
}
*func = fns;
*count = c;
return tmp;
}
:) Ok, this is a hole .c file. Yes my previous q. end this connected, becouse its a homework.
#ifndef exccel_builder_source
#define exccel_builder_source
#include "exccel_builder.h"
#include "exccel_utils.h"
#include "exccel_function.h"
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
table* _processing;
//A végére fűzi az új elemeket
void addProcess(cell_process **LIST, cell_process *new) {
if (*LIST == NULL) {
new->next = NULL;
*LIST = new;
return;
}
new->next = *LIST;
*LIST = new;
}
void build(table* table) {
int col = table->matrix->col;
int row = table->matrix->row;
int i,j;
table_cell *cellTemp;
_processing = table;
for (i = 1; i<=row; i++) {
for (j = 1; j<=col; j++) {
cellTemp = getCell(table,i,j);
if (cellTemp != NULL) {
buildCell(cellTemp);
}
}
}
}
void buildCell(table_cell *cell) {
//Begins with '='
if (isFunction(cell)) {
buildCellWithFunction(cell);
}
}
void printProcesses(cell_process *LIST, int tab) {
cell_process *tmp = NULL;
int i = 0;
tmp = LIST;
while(tmp != NULL) {
i = 0;
while(i++<tab) printf(" ");
printf("%s, %d, paramPos: %i\n",tmp->func->name,tmp->func->paramsCount,tmp->paramPos);
if (tmp->childs != NULL) {
i = 0;
while(i++<tab + 3) printf(" ");
printf("Childs\n");
printProcesses(tmp->childs, tab + 3);
}
tmp = tmp->next;
}
}
void buildCellWithFunction(table_cell *cell) {
cell_process *HEAD = NULL;
buildCellProcessList(cell,&HEAD);
cell->cp = HEAD;
printf("%d,%d - cella:\n",cell->row,cell->col);
printProcesses(HEAD,0);
}
void buildCellProcessList(table_cell *cell, cell_process **HEAD) {
char *fnString;
int size;
fnString = getCellStringValue(cell, &size);
readFn(fnString,size,1,cell,HEAD,-1);
}
int readFn(char *fnString, int n, int offset, table_cell *cell, cell_process **LIST, int paramPos) {
char *fnName, *fnParam;
int fnNameLength;
int *fnSig;
int fnSigN;
int fnSigI;
int sig;
exccel_var *vtmp;
exccel_function *ftmp;
cell_process *ptmp;
char **parameters;
int *fnIndexes;
int paramsCount;
int paramI;
int i;
fnName = readFnName(fnString,n,offset,&fnNameLength);
ftmp = getExccelFunction(fnName);
if (ftmp == NULL) {
return 0;
}
ptmp = (cell_process*)malloc(sizeof(cell_process));
ptmp->cell = cell;
ptmp->func = ftmp;
ptmp->paramPos = paramPos;
ptmp->t = _processing;
ptmp->childs = NULL;
addProcess(LIST,ptmp);
parameters = readFnParams(fnString,n,&paramsCount,&fnIndexes);
allocParams(ptmp->func,paramsCount);
paramI = 0;
fnSig = ftmp->signature;
fnSigN = fnSig[0];
fnSigI = 1;
while(fnSigI <= fnSigN) {
sig = fnSig[fnSigI];
if (sig == FN_SIG_RANGE) {
fnParam = parameters[paramI];
vtmp = createExccelRangeVarFromString(fnParam);
//addParamToFunction(ftmp,vtmp);
addParamToFunctionAtPosition(ftmp,vtmp,paramI);
paramI++;
} else if (sig == FN_SIG_LITERAL) {
fnParam = parameters[paramI];
if (fnIndexes[paramI] == 1) {
readFn(fnParam,strlen(fnParam),0,cell,&((*LIST)->childs),paramI);
} else {
vtmp = createExccelVarFromString(fnParam);
//addParamToFunction(ftmp,vtmp);
addParamToFunctionAtPosition(ftmp,vtmp,paramI);
}
paramI++;
} else if (sig == FN_SIG_LIST) {
while(paramI<paramsCount) {
fnParam = parameters[paramI];
if (fnIndexes[paramI] == 1) {
readFn(fnParam,strlen(fnParam),0,cell,&((*LIST)->childs),paramI);
} else {
vtmp = createExccelVarFromString(fnParam);
//addParamToFunction(ftmp,vtmp);
addParamToFunctionAtPosition(ftmp,vtmp,paramI);
}
paramI++;
}
} else {
printf("Invalid signature %d\n",sig);
exit(1);
}
fnSigI++;
}
return 1;
}
char *readFnName(char *fnString, int n, int offset, int *size) {
char *fnName;
int nameBuffer, i, j;
i = offset;
j = 0;
nameBuffer = 8;
fnName = (char *)calloc(nameBuffer,sizeof(char));
while(*(fnString + i) != '(' && i<n) {
*(fnName + j++) = *(fnString + i++);
if (j>=nameBuffer) {
nameBuffer += 8;
fnName = (char *)realloc(fnName, nameBuffer);
}
}
*(fnName + j++) = '\0';
*size = j;
return fnName;
}
char **readFnParams(char *fnString, int n, int *count, int **func) {
char **tmp;
int *fns = NULL;
int c,i = 0,offset,s;
c = getParamsCount(fnString,n);
if (!c) {
return NULL;
}
tmp = (char**)calloc(c,sizeof(char));
fns = (int*)calloc(c,sizeof(*fns));
offset = seekToFirstParam(fnString,n);
while(i<c) {
tmp[i] = readNextParam(fnString,n,offset,&s);
if (isFunctionString(tmp[i])) {
tmp[i] = readNextFunctionParam(fnString,n,offset,&s);
offset = seekToNextParam(fnString,n,offset + s - 1);
fns[i] = 1;
} else {
fns[i] = 0;
offset = seekToNextParam(fnString,n,offset);
}
i++;
}
*func = fns;
*count = c;
return tmp;
}
int getParamsCount(char *fnString, int n) {
int i = 0, c = 0, jump = 0;
while(i<n) {
if (fnString[i] == '(') {
jump++;
} else if (fnString[i] == ',') {
if (jump == 1) c++;
} else if (fnString[i] == ')') {
jump--;
}
i++;
}
if (c > 0) {
return c + 1;
} else {
return 1;
}
}
int seekToFirstParam(char *fnString, int n) {
int i = 0;
while(fnString[i++] != '(' && i<n);
return i;
}
int seekToNextParam(char *fnString, int n, int offset) {
int i = offset;
while(fnString[i++] != ',' && i<n);
return i;
}
char *readNextParam(char *fnString, int n, int offset, int *size) {
char *params, c;
int paramBuffer, i, j;
i = offset;
j = 0;
paramBuffer = 8;
params = (char*)calloc(paramBuffer,sizeof(char));
while((c = fnString[i++]) != ',' && c != ')' && c != '(' && i<n) {
params[j++] = c;
if (j >= paramBuffer) {
paramBuffer += 8;
params = (char*)realloc(params,paramBuffer);
}
}
params[j] = '\0';
*size = j;
return params;
}
//Megfelelő számú nyitó ( - hez kell hogy legyen ugyanannyi )
char *readNextFunctionParam(char *fnString, int n, int offset, int *size) {
char *fn, c;
int fnBf, i, j, fnStarted = 0, fnClosed = 0;
i = offset;
j = 0;
fnBf = 8;
fn = (char*)calloc(fnBf, sizeof(char));
while((fnStarted != fnClosed || fnStarted == 0) && i<n) {
c = *(fnString + i++);
if (c == '(')
fnStarted++;
else if (c == ')')
fnClosed++;
*(fn + j++) = c;
if (j >= fnBf) {
fnBf += 8;
fn = (char*)realloc(fn, sizeof(char) * fnBf);
}
}
//*(fn + j++) = ')';
*(fn + j++) = '\0';
*size = j;
return fn;
}
#endif
And input like this:
=SZORZAT(MDETERM(A1:D4),NAGY(A1:D4,0),10,20,30)
It looks to me like you aren't allocating correctly, you have:
tmp = (char**)calloc(c,sizeof(char));
The first line, tmp, is allocating c elements of size char (c elements of 1 byte), I think you want c elements of size char * (c elements of size 4 or 8 bytes per element depending on if you are 32 or 64 bit platform). Since your routine readNextParam() is returning char * to store in this array, you need to change the calloc sizeof for tmp to:
tmp = calloc(c,sizeof(char*));
Because of this, I believe you have memory overwrites when you write into the tmp array that bleed into your other array. By making both "1000" elements, you've padded out that first calloc far enough that the overwrites are still in that same piece of memory.

code with double free or corruption

I've got a double free problem in my program. I know which pointer is double freed but I cant figure out when was it freed first.
here is the code of my function :
int spectrum_gen(char *shift_r, char *rec_poly, char *redun_poly,int spectrum_length)
{
char *seq = NULL,*l_shift = NULL,loop_shift[SIZE];
int current_weight,*spectrum = NULL,*spect_numb = NULL,length=1,spectrum_size=0;
int index,index2,temp,temp2,*temp3;
/* int *weights = NULL; */
int *encoded_w = NULL;
int min_length,min_weight = 1000;
int looping = 0;
int **spectrum_content = NULL;
int *seq_w;
int *weight_table = symbols_weight(Q);
int *weights = NULL;
spectrum= (int*) malloc(sizeof(int));
seq = (char*) malloc(sizeof(char));
l_shift = (char*) malloc(SIZE*sizeof(char*));
weights = (int*) malloc(sizeof(int));
encoded_w = (int*) malloc(sizeof(int));
spect_numb = (int*) malloc(sizeof(int));
spectrum_content = (int**) malloc(sizeof(int*));
spectrum_content[1] = (int*) malloc(sizeof(int));
seq_w = (int*) malloc(sizeof(int));
strcpy(seq,"1");
convert_to_real(seq,1);
while(length > 0)
{
/* show_word(seq,length);
show_word(shift_r,SIZE);
puts(""); */
if(length == 1)
{
set2zero(shift_r,SIZE);
current_weight = RTZ_weight(0,seq[0],shift_r,rec_poly,redun_poly,encoded_w,seq_w,weight_table);
*seq_w += seq_weight(seq,1,weight_table);
}
else
{
current_weight = RTZ_weight(weights[length-2],seq[length-1],shift_r,rec_poly,redun_poly,encoded_w,seq_w,weight_table);
*seq_w += seq_weight(seq,length,weight_table);
/* show_word(shift_r,SIZE);
show_word(loop_shift,SIZE); */
if(looping==1 && str_cmp(shift_r,loop_shift,SIZE))
{
puts("looping sequence!!");
free(spectrum);
spectrum = NULL;
free(encoded_w);
encoded_w = NULL;
free(spect_numb);
spect_numb = NULL;
free(spectrum_content);
spectrum_content = NULL;
free(weights);
weights = NULL;
return 1;
break;
}
if(*encoded_w==weights[length-2] && looping==0 && length>3)
{
str_cpy(loop_shift,shift_r,SIZE);
looping = 1;
}
if(*encoded_w != weights[length-2])
{
looping = 0;
}
}
weights = realloc(weights,length*sizeof(int));
weights[length-1] = *encoded_w;
l_shift = realloc(l_shift,length*sizeof(char));
l_shift[length-1] = shift_r[SIZE-1];
if((shift_r[0] != 0) && (*encoded_w < spectrum_length))
{
if((temp = index4(current_weight,spectrum,spectrum_size,1,0)) != (-1))
{
spect_numb[temp]++;
if((temp2 = index4(*seq_w,spectrum_content[temp],spectrum_content[temp][0],2,1)) != (-1))
{ spectrum_content[temp][temp2+1]++;
}
else
{
spectrum_content[temp][0] += 2;
spectrum_content[temp] = realloc(spectrum_content[temp],spectrum_content[temp][0]*sizeof(int));
spectrum_content[temp][spectrum_content[temp][0]-2] = *seq_w;
spectrum_content[temp][spectrum_content[temp][0]-1] = 1;
}
}
else
{
spectrum_size++;
spectrum = realloc(spectrum,spectrum_size*sizeof(int));
spect_numb = realloc(spect_numb,spectrum_size*sizeof(int));
/* spectrum content : creation of a new table to store the inputs with output of weight current_weight*/
spectrum_content = realloc(spectrum_content,spectrum_size*sizeof(int*));
spectrum_content[spectrum_size-1] = (int*) malloc(3*sizeof(int));
spectrum_content[spectrum_size-1][0] = 3;
spectrum_content[spectrum_size-1][1] = *seq_w;
spectrum_content[spectrum_size-1][2] = 1;
spectrum[spectrum_size-1] = current_weight;
spect_numb[spectrum_size-1] = 1;
}
}
if(seq_equal_zero(shift_r,SIZE) || (*encoded_w >= spectrum_length))
{
while((length>0) && (seq[length-1] == Q-1))
{
length--;
for(index=0;index<SIZE-1;index++)
shift_r[index] = shift_r[index+1];
shift_r[SIZE-1] = l_shift[length-1];
}
for(index=0;index<SIZE-1;index++)
shift_r[index] = shift_r[index+1];
shift_r[SIZE-1] = l_shift[length-2];
seq[length-1] += 1;
}
else
{
length++;
seq = realloc(seq,length*sizeof(char));
seq[length-1] = 0;
}
/* printf("%d\n%d\n",*encoded_w,current_weight);
getchar(); */
}
/* sort(spectrum,spect_numb,spectrum_content,spectrum_size);*/
puts("Debut du spectre de ce codeur :");
for(index=0;spectrum[index+1]<=spectrum_length;index++)
{
printf("( ");
for(index2=1;index2<spectrum_content[index][0]-2;index2+=2)
{
printf("%d*I^%d + ",spectrum_content[index][index2+1],spectrum_content[index][index2]);
}
printf("%d*I^%d",spectrum_content[index][spectrum_content[index][0]-1],spectrum_content[index][spectrum_content[index][0]-2]);
printf(" )*O^%d + ",spectrum[index]);
}
printf("( ");
for(index2=1;index2<spectrum_content[index][0]-2;index2+=2)
{
printf("%d*I^%d + ",spectrum_content[index][index2+1],spectrum_content[index][index2]);
}
printf("%d*I^%d",spectrum_content[index][spectrum_content[index][0]-1],spectrum_content[index][spectrum_content[index][0]-2]);
printf(")*O^%d",spectrum[index]);
puts("");
free(seq);
seq = NULL;
free(spectrum);
spectrum = NULL;
free(encoded_w);
encoded_w = NULL;
free(spect_numb);
spect_numb = NULL;
free(spectrum_content);
spectrum_content = NULL;
free(weights);
weights = NULL;
return 0;
}
that pointer is called seq.
It would be so cool if someone helps me with this :)
here are the two functions that handle that pointer
void convert_to_real(char *word,int end)
{
int index;
for(index=0;index<end;index++) word[index]-='0';
}
i dont think it may be a problem
the only other function that handles that pointer is :
int seq_weight(char *seq,int end,int *weight_table)
{
int index,weight = 0;
for(index=0;index<end;index++)
if(seq[index]>=0 && seq[index]<Q)
weight += weight_table[(int)seq[index]];
return weight;
}
and i dont think it would cause a problem neither. :(
It's great that you set the pointer value to null after you have free'd it. So make use of that fact, and check for null before you free it - that way you avoid the double delete. Then you don't have to hunt for the double deletion because you will be protected from it.

Resources