Memory Lost Valgrind [closed] - c

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I have a memory lost problem I can not solve:
==19660== 14,583 (1,764 direct, 12,819 indirect) bytes in 49 blocks are definitely lost in loss record 27 of 27
==19660== at 0x4023F50: malloc (vg_replace_malloc.c:236)
==19660== by 0x80489F5: AllocateFct (function.c:27)
==19660== by 0x804BB51: InsertFct (reader.c:417)
==19660== by 0x804BFFB: InsertShape (reader.c:591)
==19660== by 0x804AEED: main (main.c:103)
Generating by the following features :
function AllocateFct(char* model)
{
function fct = (function) malloc(sizeof(struct _function_));
if (fct == NULL)
return NULL;
if (model==NULL)
fct->model = NULL;
else
{
fct->model = malloc(sizeof(char) * (strlen(model) + 1));
fct->model[0] = '\0';
if (fct->model==NULL){
fprintf(stderr,"Not enough memory!\n");
exit(1);
}
strcpy(fct->model, model);
}
fct->detail = NULL;
fct->brief = NULL;
fct->bug = NULL;
fct->f = NULL;
fct->Parameter = NULL;
fct->ret = NULL;
fct->def = NULL;
fct->next = NULL;
return fct;
}
=============================
void InsertFct(function* fct, content c)
{
if (type > 0)
{
type = c.code;
(*fct)->def = (char*) malloc(sizeof(char) * (strlen(c.message) + 1));
(*fct)->def[0]='\0';
if ((*fct)->def==NULL){
fprintf(stderr,"Not enough memory!\n");
exit(1);
}
strcpy((*fct)->def, c.message);
return;
}
switch (c.code)
{
case FN:
type = 0;
*fct = AllocateFct(c.message);
break;
case PARAM:
type = 0;
AddParameterFunction(*fct, c.message);
break;
case BRIEF:
type = 0;
AddBriefFunction(*fct, c.message);
break;
case DETAILS:
type = 0;
AddDetailFunction(*fct, c.message);
break;
case RETURN:
AddRetourFunction(*fct, c.message);
break;
case BUG:
type = 0;
AddBugFunction(*fct, c.message);
break;
default:
type = c.code;
AddDefautFunction(*fct,c.message);
break;
}
}
===========================
int InsertShape(list heading, list source, shape* finalShape, shape* tmp)
{
fileRead* file = NULL;
shape s = NULL;
shape insert = AllocateShape(NULL);
function fct = AllocateFct(NULL);
function fctlist = NULL;
int i = 0;
int j = 0;
int pile = 0;
int n = 0;
int tag = 0;
list headerlist = NULL;
content c;
char chaine;
if (heading != NULL )
{
char* recover = (char*) GetNameFile(heading->name);
s = AllocateShape(recover);
free(recover);
recover=NULL;
}
else if (source != NULL )
{
char* recover = (char*) GetNameFile(source->name);
s = AllocateShape(recover);
free(recover);
recover=NULL;
}
if (heading != NULL )
{
file = OpenFileRead(heading->name);
n = CheckInclude(file->f, &headerlist);
if (n == 0)
n = 1;
fseek(file->f, -n, SEEK_CUR);
do
{
i = 0;
j = RecoverComments(file, &c, &tag);
InsertFct(&fct, c);
if(c.message!=NULL){
free(c.message);
c.message=NULL;
}
if (type > 0)
AddToShape(insert, fct);
if (j == -5 && i == 0)
{
type = 0;
do
{
if (fscanf(file->f, "%c", &chaine) == EOF)
{
i = 0;
break;
}
} while (chaine == ' ' || chaine == '\n');
if (chaine == '/')
{
i = 1;
j = 0;
fseek(file->f, -1, SEEK_CUR);
}
}
if (i == 0 && (j == -5))
{
if (type == 0)
{
pile++;
fctlist = AddFunction(fctlist, fct);
}
else
type = 0;
}
} while (j != -3);
FreefileRead(file);
}
i = 0;
j = 0;
type = 0;
if (source != NULL )
{
file = OpenFileRead(source->name);
n = CheckInclude(file->f, &headerlist);
if (n == 0)
n = 1;
fseek(file->f, -n, SEEK_CUR);
do
{
i = 0;
j = RecoverComments(file, &c, &tag);
InsertFct(&fct, c);
if(c.message!=NULL){
free(c.message);
c.message=NULL;
}
if (type > 0)
AddToShape(insert, fct);
if (j == -5 && i == 0)
{
type = 0;
do
{
if (fscanf(file->f, "%c", &chaine) == EOF)
{
i = 0;
break;
}
} while (chaine == ' ' || chaine == '\n');
if (chaine == '/')
{
i = 1;
j = 0;
fseek(file->f, -1, SEEK_CUR);
}
}
if (i == 0 && (j == -5))
{
if (type == 0)
fctlist = TourAndChange(fctlist, fct);
else
type = 0;
}
} while (j != -3);
FreefileRead(file);
}
s->fctList = AddFunction(s->fctList, fctlist);
s->headerList = headerlist;
*finalShape = CreateListShape(*finalShape, s);
*tmp = CreateListShape(*tmp, insert);
return 1;
}
=====================
The part concerned in the main :
InsertShape(tmpheading, tmproot, &s, &s2);
if (heading == NULL){
tmpheading = NULL;
}
if (root == NULL){
tmproot = NULL;
}
}
Thank you in advance for your response.

Well when do you ever free it? It doesn't look like you have a single free in your code! (Except for "freefileread", but we have no clue what that does and it doesn't seem designed for that function!)

Things I noticed:
fct->model = malloc(sizeof(char) * (strlen(model) + 1));
fct->model[0] = '\0';
if (fct->model==NULL){
fprintf(stderr,"Not enough memory!\n");
exit(1);
}
strcpy(fct->model, model);
Here the fct->model[0] = '\0'; could be dereferencing a null pointer. It should be removed. Also, this block of code could be replaced with a call to strdup.
void InsertFct(function* fct, content c)
{
if (type > 0)
... what is type? Some kind of global? Bad design if so.
The code following this could, again, be replaced with a call to strdup.
InsertShape(tmpheading, tmproot, &s, &s2);
if (heading == NULL){
tmpheading = NULL;
}
if (root == NULL){
tmproot = NULL;
}
Why do you set the pointers to NULL without freeing them first? BTW, free(NULL) does nothing, so you don't have to do something like if(ptr) free(ptr);... just call free(ptr);.

Related

Realloc: resetting flexable array of struct within a struct

I been banging my head on the wall with this one. I was able to narrow it down to the realloc portion of my code.
CalStatus readCalComp( FILE *const ics, CalComp **const pcomp )
{
CalStatus test;
CalProp * foldLine;
CalProp * temp;
CalComp ** subComp;
char * buffer;
static int depth = 0;
int count = 0;
int i = 0;
buffer = NULL;
foldLine = NULL;
subComp = NULL;
if (depth == 0)
{
test = readCalLine (ics, &buffer);
if (buffer == NULL)
{
return test;
}
foldLine = malloc (sizeof (CalProp));
assert (foldLine != NULL);
test.code = parseCalProp (buffer, foldLine);
free (buffer);
if ((strcmp ("BEGIN", foldLine->name) == 0) && ((strcmp ("VCALENDAR", foldLine->value) == 0)))
{
(*pcomp)->name = malloc (sizeof(char) * strlen(foldLine->value)+1);
assert ((*pcomp)->name != NULL);
strcpy((*pcomp)->name, foldLine->value);
depth = depth + 1;
free(foldLine->name);
free(foldLine->value);
free(foldLine);
while ((buffer != NULL) && (test.code == OK) && (depth > 0))
{
test = readCalLine (ics, &buffer);
if (buffer != NULL)
{
foldLine = malloc (sizeof(CalProp));
assert (foldLine != NULL);
test.code = parseCalProp (buffer, foldLine);
free (buffer);
if ((strcmp ("END", foldLine->name) == 0) && ((strcmp ("VCALENDAR", foldLine->value) == 0) || (strcmp ("VCALENDAR\r\n", foldLine->value) == 0) ))
{
depth = depth - 1;
free(foldLine->name);
free(foldLine->value);
free(foldLine);
return test;
}
else if (strcmp ("BEGIN", foldLine->name) == 0)
{
subComp = malloc(sizeof (CalComp *));
*subComp = malloc(sizeof(CalComp) + (1*sizeof(CalComp*)));
(*subComp)-> name = NULL;
(*subComp)-> nprops = 0;
(*subComp)-> prop = NULL;
(*subComp)-> ncomps = 0;
(*subComp)-> comp[0] = NULL;
(*subComp)-> name = malloc(sizeof(char) *strlen(foldLine->value)+1);
strcpy((*subComp)->name, foldLine->value);
if ((*pcomp)-> ncomps == 0)
{
(*pcomp)->comp[(*pcomp)->ncomps] = *subComp;
(*pcomp)->ncomps += 1;
}
else
{
(*pcomp)->ncomps += 1;
*pcomp = realloc(*pcomp, sizeof(CalComp) + (2*sizeof(CalComp*)));
(*pcomp)->comp[(*pcomp)->ncomps-1] = *subComp;
}
depth = depth + 1;
test = readCalComp (ics, subComp);
}
} // end of if buffer NULL
}// end of While
} // end of if VCALENDAR
} // End of if Depth
else
{
if (count == 0)
{
test = readCalLine (ics, &buffer);
count += 1;
}
while ((test.code == OK) && (buffer != NULL))
{
if (count != 1)
{
test = readCalLine (ics, &buffer);
}
else
{
count = 0;
}
if (buffer != NULL)
{
foldLine = malloc (sizeof(CalProp));
test.code = parseCalProp (buffer, foldLine);
free (buffer);
if ((strcmp ("END", foldLine->name) == 0) && ((strcmp ((*pcomp)->name, foldLine->value) == 0)))
{
depth = depth - 1;
free (foldLine->name);
free (foldLine->value);
free (foldLine);
return test;
}
else if (strcmp ("BEGIN", foldLine->name) == 0)
{
printf("Success in malloc 2!\n");
subComp = malloc(sizeof (CalComp *));
*subComp = malloc(sizeof(CalComp) + (1*sizeof(CalComp*)));
(*subComp)-> name = NULL;
(*subComp)-> nprops = 0;
(*subComp)-> prop = NULL;
(*subComp)-> ncomps = 0;
(*subComp)-> comp[0] = NULL;
(*subComp)-> name = malloc(sizeof(char) *strlen(foldLine->value)+1);
strcpy ((*subComp)->name, foldLine->value);
if ((*pcomp)-> ncomps == 0)
{
(*pcomp)->comp[(*pcomp)->ncomps] = *subComp;
(*pcomp)->ncomps += 1;
}
else
{
(*pcomp)->ncomps += 1;
(*pcomp) = realloc(*pcomp, sizeof(CalComp) + (2*sizeof(CalComp*)));
(*pcomp)->comp[(*pcomp)->ncomps-1] = *subComp;
printf ("First subcomponent is %s\n", (*pcomp)->comp[0]->name);
printf ("Second subcomponent is %s\n", (*pcomp)->comp[1]->name);
}
depth = depth + 1;
test = readCalComp (ics, subComp);
}
}
}
}
return test;
}
CalComp is a struct that consists of:
char * name;
int numProps;
CalProp *prop (linked list);
int numComp;
CalComp *comp[] (flexible array);
Checking inside the function, the name of the structs within the flexible array is correct, but when I try to access the names outside of the function, it either NULL value or been set to the name of the first linked list node of the structure.
Due to the nature of the assignment, I can not modify Calcomp struct nor the function parameters. The function must be recursive, and the flexible array must adjust based on need.
As I said before, I narrowed it down to the realloc, by printing out the values within the flexible array. The bug occurs when the program reallocs.
FYI, I have tried reallocing to a temp variable, checked to see if NULL and then assigned that one to pcomp but didn't help.
When you call realloc, you're not including ncomp in the additional size for the flexible structure, you're just hard-coding it to 2.
(*pcomp) = realloc(*pcomp, sizeof(CalComp) + (*pcomp->ncomps * sizeof(CalComp*)));
(*pcomp) = realloc(*pcomp, sizeof(CalComp) + (2*sizeof(CalComp*)));
change above line to
pcomp = realloc(*pcomp, sizeof(CalComp) + (2*sizeof(CalComp*)));

Printing string pointers in c

So, essentially I have two files:
File 1:
//
// main.c
// frederickterry
//
// Created by Rick Terry on 1/15/15.
// Copyright (c) 2015 Rick Terry. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int size (char *g) {
int ofs = 0;
while (*(g+ofs) != '\0') {
++ofs;
}
return ofs;
}
int parse(char *g) {
// Setup
char binaryConnective;
int negated = 0;
// Looking for propositions
int fmlaLength = size(g);
if(fmlaLength == 0) {
return 1;
}
if(fmlaLength == 1) {
if(g[0] == 'p') {
return 1;
} else if (g[0] == 'q') {
return 1;
} else if (g[0] == 'r') {
return 1;
} else {
return 0;
}
}
// Now looking for negated preposition
if(fmlaLength == 2) {
char temp[100];
strcpy(temp, g);
if(g[0] == '-') {
negated = 1;
int negatedprop = parse(g+1);
if(negatedprop == 1) {
return 2;
}
}
}
// Checking if Binary Formula
char arrayleft[50];
char arrayright[50];
char *left = "";
char *right = "";
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int binarypresent = 0;
if(fmlaLength != 1 && fmlaLength != 2) {
if(g[0] == '-') {
int negatedBinary = parse(g+1);
if(negatedBinary == 1 || negatedBinary == 2 || negatedBinary == 3) {
return 2;
} else {
return 0;
}
}
int i = 0;
int l = 0;
int p = strlen(g);
for(l = 0; l < strlen(g)/2; l++) {
if(g[l] == '(' && g[p-l-1] == ')') {
i++;
}
}
for(int q = i; q < strlen(g); q++) {
if(g[q] == '(') {
numLeft++;
} else if(g[q] == ')') {
numRight++;
}
arrayleft[q] = g[q];
//printf("%c", arrayleft[i]);
//printf("%s", left);
if((numRight == numLeft) && (g[q+1] == 'v' || g[q+1] == '>' || g[q+1] == '^')) {
arrayleft[q+1] = '\0';
bclocation = q+1;
binaryConnective = g[q+1];
binarypresent = 1;
// printf("The binary connecive is: %c\n", binaryConnective);
break;
}
}
if(binarypresent == 0) {
return 0;
}
int j = 0;
for(int i = bclocation+1; i < strlen(g)-1; i++) {
arrayright[j] = g[i];
j++;
}
arrayright[j] = '\0';
left = &arrayleft[1];
right = &arrayright[0];
//printf("Printed a second time, fmla 1 is: %s", left);
int parseleft = parse(left);
// printf("Parse left result: %d\n", parseleft);
if(parseleft == 0) {
return 0;
}
int parseright = parse(right);
if(parseright == 0) {
return 0;
}
// printf("Parse right result: %d\n", parseleft);
if(negated == 1) {
return 2;
} else {
return 3;
}
}
return 0;
}
int type(char *g) {
if(parse(g) == 1 ||parse(g) == 2 || parse(g) == 3) {
if(parse(g) == 1) {
return 1;
}
/* Literals, Positive and Negative */
if(parse(g) == 2 && size(g) == 2) {
return 1;
}
/* Double Negations */
if(g[0] == '-' && g[1] == '-') {
return 4;
}
/* Alpha & Beta Formulas */
char binaryConnective;
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int binarypresent = 0;
int i = 0;
if(g[0] == '(') {
i++;
}
if(g[0] == '-') {
i++;
if(g[1] == '(') {
i++;
}
}
for(i; i < strlen(g); ++i) {
if(g[i] == '(') {
numLeft++;
} else if(g[i] == ')') {
numRight++;
}
if(numRight == numLeft) {
if(g[i+1] == 'v' || g[i+1] == '>' || g[i+1] == '^') {
bclocation = i+1;
binaryConnective = g[i+1];
binarypresent = 1;
break;
}
}
}
/* Connective established */
if(binaryConnective == '^') {
if(g[0] == '-') {
return 3;
} else {
return 2;
}
} else if(binaryConnective == '>') {
if(g[0] == '-') {
return 2;
} else {
return 3;
}
} else if (binaryConnective == 'v') {
if(g[0] == '-') {
return 2;
} else {
return 3;
}
}
}
return 0;
}
char bin(char *g) {
char binaryConnective;
char arrayLeft[50];
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int i = 0;
if(g[0] == '(') {
i++;
}
if(g[0] == '-') {
i++;
if(g[1] == '(') {
i++;
}
}
for(i; i < strlen(g); ++i) {
if(g[i] == '(') {
numLeft++;
} else if(g[i] == ')') {
numRight++;
}
int j = 0;
arrayLeft[j++] = g[i];
if(numRight == numLeft) {
if(g[i+1] == 'v' || g[i+1] == '>' || g[i+1] == '^') {
arrayLeft[i+1] = '\0';
bclocation = i+1;
binaryConnective = g[i+1];
return binaryConnective;
}
}
}
return binaryConnective;
}
char *partone(char *g) {
char binaryConnective;
char arrayLeft[50];
char arrayRight[50];
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int i = 0;
if(g[0] == '(') {
i++;
}
if(g[0] == '-') {
i++;
if(g[1] == '(') {
i++;
}
}
int j = 0;
for(i; i < strlen(g); ++i) {
if(g[i] == '(') {
numLeft++;
} else if(g[i] == ')') {
numRight++;
}
arrayLeft[j] = g[i];
if(numRight == numLeft) {
if(g[i+1] == 'v' || g[i+1] == '>' || g[i+1] == '^') {
arrayLeft[j+1] = '\0';
bclocation = i+1;
binaryConnective = g[i+1];
break;
}
}
j++;
}
int m = 0;
for(int k = bclocation+1; k < strlen(g)-1; k++) {
arrayRight[m] = g[k];
m++;
}
arrayRight[m] = '\0';
char* leftSide = &arrayLeft[0];
// printf("%s\n", leftSide);
// printf("%s\n", rightSide);
int k = 0;
k++;
return leftSide;
}
char *parttwo(char *g) {
char binaryConnective;
char arrayLeft[50];
char arrayRight[50];
int numLeft = 0;
int numRight = 0;
int bclocation = 0;
int i = 0;
if(g[0] == '(') {
i++;
}
if(g[0] == '-') {
i++;
if(g[1] == '(') {
i++;
}
}
int j = 0;
for(i; i < strlen(g); ++i) {
if(g[i] == '(') {
numLeft++;
} else if(g[i] == ')') {
numRight++;
}
arrayLeft[j] = g[i];
if(numRight == numLeft) {
if(g[i+1] == 'v' || g[i+1] == '>' || g[i+1] == '^') {
arrayLeft[j+1] = '\0';
bclocation = i+1;
binaryConnective = g[i+1];
break;
}
}
j++;
}
int m = 0;
int n = size(g) - 1;
if(g[strlen(g)-1] != ')') {
n++;
}
for(int k = bclocation+1; k < n; k++) {
arrayRight[m] = g[k];
m++;
}
arrayRight[m] = '\0';
char* leftSide = &arrayLeft[0];
char* rightSide = &arrayRight[0];
// printf("%s\n", leftSide);
// printf("%s\n", rightSide);
return rightSide;
}
char *firstexp(char *g) {
char* left = partone(g);
char leftArray[50];
int i = 0;
for(i; i < strlen(left); i++) {
leftArray[i] = left[i];
}
leftArray[i] = '\0';
char binConnective = bin(g);
int typeG = type(g);
if(typeG == 2) {
if(binConnective == '^') {
return &leftArray;
} else if(binConnective == '>') {
return &leftArray;
}
} else if(typeG == 3) {
if(binConnective == 'v')
return &leftArray;
}
char temp[50];
for(int i = 0; i < strlen(leftArray); i++) {
temp[i+1] = leftArray[i];
}
temp[0] = '-';
char* lefttwo = &temp[0];
if(typeG == 2) {
if(binConnective == 'v') {
return lefttwo;
}
} else if(typeG == 3) {
if(binConnective == '>' || binConnective == '^') {
return lefttwo;
}
}
return "Hello";
}
char *secondexp(char *g) {
// char binaryConnective = bin(g);
// char* right = parttwo(g);
// char rightArray[50];
// int i = 0;
// for(i; i< strlen(right); i++) {
// rightArray[i+1] = right[i];
// }
// rightArray[i] = '\0';
// int typeG = type(g);
// if(type(g) == 2) {
// if(binaryConnective == '^') {
// return &rightArray;
// }
// } else if(type(g) == 3) {
// if(binaryConnective == 'v' || binaryConnective == '>') {
// return &rightArray;
// }
// }
return "Hello";
}
typedef struct tableau tableau;
\
\
struct tableau {
char *root;
tableau *left;
tableau *right;
tableau *parent;
int closedbranch;
};
int closed(tableau *t) {
return 0;
}
void complete(tableau *t) {
}
/*int main(int argc, const char * argv[])
{
printf("Hello, World!\n");
printf("%d \n", parse("p^q"));
printf("%d \n", type("p^q"));
printf("%c \n", bin("p^q"));
printf("%s\n", partone("p^q"));
printf("%s\n", parttwo("p^q"));
printf("%s\n", firstexp("p^q"));
printf("Simulation complete");
return 0;
}*/
File 2:
#include <stdio.h>
#include <string.h> /* for all the new-fangled string functions */
#include <stdlib.h> /* malloc, free, rand */
#include "yourfile.h"
int Fsize = 50;
int main()
{ /*input a string and check if its a propositional formula */
char *name = malloc(Fsize);
printf("Enter a formula:");
scanf("%s", name);
int p=parse(name);
switch(p)
{case(0): printf("not a formula");break;
case(1): printf("a proposition");break;
case(2): printf("a negated formula");break;
case(3): printf("a binary formula");break;
default: printf("what the f***!");
}
printf("\n");
if (p==3)
{
printf("the first part is %s and the second part is %s", partone(name), parttwo(name));
printf(" the binary connective is %c \n", bin(name));
}
int t =type(name);
switch(t)
{case(0):printf("I told you, not a formula");break;
case(1): printf("A literal");break;
case(2): printf("An alpha formula, ");break;
case(3): printf("A beta formula, ");break;
case(4): printf("Double negation");break;
default: printf("SOmewthing's wrong");
}
if(t==2) printf("first expansion fmla is %s, second expansion fmla is %s\n", firstexp(name), secondexp(name));
if(t==3) printf("first expansion fmla is %s, second expansion fmla is %s\n", firstexp(name), secondexp(name));
tableau tab;
tab.root = name;
tab.left=0;
tab.parent=0;
tab.right=0;
tab.closedbranch=0;
complete(&tab);/*expand the root node then recursively expand any child nodes */
if (closed(&tab)) printf("%s is not satisfiable", name);
else printf("%s is satisfiable", name);
return(0);
}
If you look at the first file, you'll see a method called * firstexp(char * g).
This method runs perfectly, but only if another method called * secondexp(char * g) is commented out.
If * secondexp(char * g) is commented out, then *firstexp runs like this:
Enter a formula:((pvq)>-p)
a binary formula
the first part is (pvq) and the second part is -p the binary connective is >
A beta formula, first expansion fmla is -(pvq), second expansion fmla is Hello
((pvq)>-p) is satisfiableProgram ended with exit code: 0
otherwise, if *secondexp is not commented out, it runs like this:
Enter a formula:((pvq)>-p)
a binary formula
the first part is (pvq) and the second part is -p the binary connective is >
A beta formula, first expansion fmla is \240L, second expansion fmla is (-
((pvq)>-p) is satisfiable. Program ended with exit code: 0
As you can see, the outputs are completely different despite the same input. Can someone explain what's going on here?
In the commented-out parts of secondexp and in parttwo, you return the address of a local variable, which you shouldn't do.
You seem to fill a lot of ad-hoc sized auxiliary arrays. These have the problem that they might overflow for larger expressions and also that you cannot return them unless you allocate them on the heap with malloc, which also means that you have to free them later.
At first glance, the strings you want to return are substrings or slices of the expression string. That means that the data for these strings is already there.
You could (safely) return pointers into that string. That is what, for example strchr and strstr do. If you are willing to modify the original string, you could also place null terminators '\0' after substrings. That's what strtok does, and it has the disadvantage that you lose the information at that place: If you string is a*b and you modify it to a\0b, you will not know which operator there was.
Another method is to create a struct that stores a slice as pointer into the string and a length:
struct slice {
const char *p;
int length;
};
You can then safely return slices of the original string without needing to worry about additional memory.
You can also use the standard functions in most cases, if you stick to the strn variants. When you print a slice, you can do so by specifying a field width in printf formats:
printf("Second part: '%.*s'\n", s->length, s->p);
In your parttwo() function you return the address of a local variable
return rightSide;
where rightSide is a pointer to a local variable.
It appears that your compiler gave you a warning about this which you solved by making a pointer to the local variabe arrayRight, that may confuse the compiler but the result will be the same, the data in arrayRight will no longer exist after the function returns.
You are doing the same all over your code, and even worse, in the secondexp() function you return a the address of a local variable taking it's address, you are not only returning the address to a local variabel, but also with a type that is not compatible with the return type of the function.
This is one of many probable issues that your code may have, but you need to start fixing that to continue with other possible problems.
Note: enable extra warnings when compiler and listen to them, don't try to fool the compiler unless you know exactly what you're doing.

How to free char** array that allocated in calling function from main?

this is the function that i am calling from main:
char** readTokens(char *userInput, const char *seperator)
{
char** c;
char line1[512],line2[512];
int wordCount = 0;
int index;
char* tmp;
strcpy(line1, userInput);
for (index=0;line1[index]!='\n';index++);
line1[index]='\0';
strcpy(line2,line1);
tmp = strtok(line1,seperator);
while (tmp!=NULL)
{
tmp=strtok(NULL,seperator);
wordCount = wordCount + 1;
}
if((wordCount) == ERROR)
{
return NULL;
}
c=(char**)malloc(((wordCount)+1)*sizeof(char*));
if (c == NULL)
{
printf("failed to allocate memory.\n");
return NULL;
}
tmp = strtok(line2,seperator);
index=0;
while (tmp!=NULL)
{
c[index]=(char*)malloc((strlen(tmp)+1*sizeof(char)));
if (c[index]==NULL)
{
printf("failed to allocate memory.\n");
return NULL;
}
strcpy(c[index],tmp);
tmp=strtok(NULL,seperator);
index++;
}
c[index] = NULL;//put NULL on last place
return c;
}
And this how i use it in main:
while (fgets(words, sizeof(words), filePointer) != NULL) // this line is a command of reading a line from the file.
{
/*here i am calling the function*/
array = readTokens(words, " ");
theGraph->graphEdges[index_i].sourceVertex = array[ZERO];
theGraph->graphEdges[index_i].destinationVertex = array[ONE];
theGraph->graphEdges[index_i].arcValue = atoi(array[TWO]);
for(index_j = ZERO ; index_j < vertexes ; index_j++)
{
if(theGraph->placeInTableIndex[index_j] == NULL)
{
theGraph->placeInTableIndex[index_j] = array[ZERO];
break;
}
else if(strcmp(theGraph->placeInTableIndex[index_j],array[ZERO]) == ZERO)
break;
}
for(index_j = ZERO ; index_j < vertexes ; index_j++)
{
if(theGraph->placeInTableIndex[index_j] == NULL)
{
theGraph->placeInTableIndex[index_j] = array[ONE];
break;
}
else if(strcmp(theGraph->placeInTableIndex[index_j],array[ONE]) == ZERO)
break;
}
theGraph->graphEdges[index_i+ONE].sourceVertex = array[ONE];
theGraph->graphEdges[index_i+ONE].destinationVertex = array[ZERO];
theGraph->graphEdges[index_i+ONE].arcValue = atoi(array[TWO]);
index_i+= TWO;
//freeTokens(array);
}
I tried to do free to the array in the end of the while but it not work i still have memory leak from this function (valgrind check). i am using this function to free:
void freeTokens(char** tokens)
{
while(*tokens != NULL)
{
*tokens = NULL;
free(*tokens);
*tokens++;
}
tokens = NULL;
free(tokens);
}
You're losing the original value of tokens (the thing you need to free) by incrementing it; then you set it to NULL, then try to free NULL.
Instead:
void freeTokens(char** tokens)
{
char **freeTokens = tokens;
while (*freeTokens != NULL)
{
free(*freeTokens);
*freeTokens = NULL; // not actually necessary, but must happen *after* if at all
freeTokens++;
}
free(tokens);
// tokens = NULL; // accomplishes nothing; doesn't change the caller's version
}

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.

Segfault on fscanf

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 );

Resources