Coredump in selfmade arrayList - c

i'm current working on a homework assesment where i'm programming a program ment to stitch textfiles with a piece of an ascii image to create a complete image of all the pieces. The way i intended to write the code is having a while loop looking through a directory finding the parts and adding them to an array. However in my AddFile method(or when i call it to be precise) i get a coredump.. I just started working with c so i dont know if it is very obvious to some of you why i get a coredump or more complicated. Also, i originaly wrote the addFile method to use and accept int's instead of the FILE type, at that point it worked perfectly without any coredumps so i suspect (but hey i might be wrong) that it went wrong when i tried to implement it with the FILE type.
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int listSize;
int listCapacity;
FILE *fileStream;
}FileList;
void addFile(FileList* list, FILE file)
{
if((*list).listSize<(*list).listCapacity)
{
(*list).fileStream[(*list).listSize]=file;
(*list).listSize+=1;
}
else
{
FILE *tempArray = calloc((*list).listSize,sizeof(FILE));
for(int i=0; i<(*list).listSize; i++)
{
tempArray[i]=(*list).fileStream[i];
}
//Do something with array...
free((*list).fileStream);
(*list).listCapacity=((*list).listCapacity)*2;
(*list).fileStream=calloc((*list).listCapacity,sizeof(FILE));
for(int i=0; i<(*list).listSize; i++)
{
(*list).fileStream[i]=tempArray[i];
}
(*list).fileStream[(*list).listSize]=file;
(*list).listSize+=1;
free(tempArray);
}
}
int main()
{
FileList intList;
intList.listSize=0;
intList.listCapacity=1;
intList.fileStream=calloc(intList.listCapacity,sizeof(int));
int fileYcoord=0;
int fileXcoord=0;
while(1)
{
char fileName [100];
int fileNameLength=sprintf(fileName,"part_%02d-%02d",fileXcoord,fileYcoord);
FILE * pFile = fopen (fileName,"r");
if(pFile!=NULL)
{
printf("- ! found file: %s - name length : %d \n",fileName,fileNameLength);
addFile(&intList,*pFile);
fclose(pFile);
fileXcoord++;
}
else
{
if(fileXcoord!=0)
{
fileYcoord+=1;
fileXcoord=0;
}
else
{
break;
}
}
}
printf("size %d , %d",fileXcoord, fileYcoord);
free(intList.fileStream);
return 0;
}

The call to addFile() is dereferencing a FILE *, producing a value of type FILE. This is wrong, this is an opaque type and should always be handled by pointers.

Related

how to change the program to do the same task without the program crashing?

I have an assignment to produce a program that will compare students answer to the answer key, and display the incorrect answers. The program then produces a report of the students incorrect answers and his final grade. The Program must use arrays and functions.
Currently I am trying to code two functions one to read the students answer file and store it in an array and the other to read answer key file and store it in another array. Then the functions will return both arrays to the main function later to be sent to another function to compare their contents(not yet done).
My problem with this code after pressing F11 to compile and run, i get a blank execution screen and a notification saying that the program has stopped working.
If my code contains a mistake or my approach is incorrect please tell me how to fix it.
note: this is my first semester learning C programming.
Thank you.
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<stdlib.h>
//Modules
char* readstudent()
{
FILE*s_ans;
int i,j;
static char arrs[20];
s_ans=fopen("trial2.txt","r");
if (s_ans == NULL)//check if file can be opened
{
printf("error student");
}
while(!feof(s_ans))
{
for(j=0;j<20;j++)
{
fscanf(s_ans,"%s",arrs[j]);
}
}
printf("ReadStudent\n");
for(i=0;i<20;i++)
{
printf("%d\t %s\n",i+1,arrs[i]);
}
return arrs;
}
char* readcorrect()
{
FILE*c_ans;
int x,i;
static char arrc[20];
c_ans=fopen("CorrectAnswers.txt","r");
if (c_ans == NULL)//check if file can be opened
{
printf("error correct");
}
while(!feof(c_ans))
{
for(x=0;x<20;x++)
{
fscanf(c_ans,"%s",arrc[x]);
}
}
printf("ReadCorrect\n");
for(i=0;i<20;i++)
{
printf("%d\t %s\n",i+1,arrc[i]);
}
return arrc;
}
//Main
int main()
{
int i,j,n,x;
char* as_ans=readstudent();
char* ac_ans=readcorrect();
printf("Main");
for(i=0;i<20;i++)
{
printf("%s",as_ans[i]);
}
return 0;
}

Allocation to Pointers

I work with char ****pCourses
int Courses(char ****pCourses, int ****pGrades, int **pCount, int *count)
{
char *buffer=NULL;
char letter;
int j=0, i;
int size=20;
int countCourse=0, sumCourses=0;
buffer=(char *)malloc(size*sizeof(char));
do
{
scanf("%c",&letter);
}while(letter==32);
while(letter!=10)
{
while(letter!=',')
{
//in case we need to expend the buffer
if(j>size)
{
size*=2;
buffer=(char *)realloc(buffer,size*sizeof(char));
}
buffer[j]=letter;
j++;
//The new letter from the name of course
scanf("%c",&letter);
}
//The end of the name of course
buffer[j]='\0';
j=0;
if(countCourse==0)
{
*pCount=(int *)realloc(*pCount, ((*count)+1)*sizeof(int));
(*pCount)[*count]=1;
}
else
(*pCount)[*count]++;
//Add the course's name to the system
*pCourses=(char ***)realloc(*pCourses, ((*count)+1)*sizeof(char ***));
(*pCourses)[*count]=(char **)realloc((*pCourses)[*count],(countCourse+1)*sizeof(char *));
((*pCourses)[*count])[countCourse]=(char *)malloc(strlen(buffer)+1);
strcpy(((*pCourses)[*count])[countCourse], buffer);
countCourse++;
scanf("%c",&letter);
}
free(buffer);
return 0;
}
while running I get a problem because of the next line:
(*pCourses)[*count]=(char **)realloc((*pCourses)[*count],(countCourse+1)*sizeof(char *));
that leads me to this part (from dbgheap.c):
{
while (nSize--)
{
if (*pb++ != bCheck)
{
return FALSE;
}
}
return TRUE;
}
does someone know what it means or why does this happen?
I think you've already been told what the problem is. All the alloc-type functions can fail and you should test for that and ideally write code that is robust enough to code with a failure.
Note that repeatedly using realloc() is not a good idea. If you expect to have to repeatedly add ( or remove ) data then you should be using a different structure, like a linked list or tree, which are designed to allow adding and removing data on the fly.

Error with content being read out of file

Hello fellow programmers i am trying to understand what exactly is happening in this area of my code.
Problem: I read some contents into a file , then i am trying to read back the contents out of the file just to make sure its the right contents i had put into the file but it is not giving me the correct output, so i am a little confused here is the code(saved content as binary) :
typedef struct acc
{
int id_no;
int pin;
float bal;
}Acc;
int Crte_acc(FILE *flepss)
{
int i,cnt;
Acc user[1000];
cnt = 1000;
for (i=1;i<1000;i++)
{
cnt+=1;
user[i].id_no = cnt;
user[i].bal=1000;
user[i].pin=0000;
fwrite(&user[i].id_no,sizeof(int),1,flepss);
fwrite(&user[i].pin,sizeof(int),1,flepss);
fwrite(&user[i].bal,sizeof(int),1,flepss);
}
return fclose(flepss);
}
Yea so above is the code that takes a file pointer and a count to keep the id to increase by 1 ( 1001,1002 etc), bal and pin required that i set the var with those digits.So i am wondering whats the problem, this is the code of me displaying the contents.
void DisplyFile()
{
FILE *dfp;
int x;
Acc pruser[1000];
dfp = fopen("Account.dat","rb");
fseek(dfp,0,SEEK_SET);
while (1)
{
if(!feof(dfp))
{
for (x=1;x<1000;x++)
{
fread(&pruser[x].id_no,sizeof(pruser[x].id_no),1,dfp);
fread(&pruser[x].pin,sizeof(pruser[x].pin),1,dfp);
fread(&pruser[x].bal,sizeof(pruser[x].bal),1,dfp);
printf("%d ",pruser[x].id_no);
printf("%d ",pruser[x].pin);
printf("%.2f\n\n",pruser[x].bal);
}
}
else
{
break;
}
}
}
EDIT: By contents coming out wrong i mean , giving me garbage values as to show that my write to file was not saved.
The problem may come from a missing fclose or fopen...
There is almost nothing to do to build something that works.
Three things to check :
-Does a fopen correspond to a fclose ?
-Are opening types similar ? Are both "wb" and "rb" used ?
-Another point is fwrite(&user[i].bal,sizeof(int),1,flepss);...bla is a float. float and int may have the same sizeof, but...It is safer to assume that it is not always the case !
#include <stdio.h>
typedef struct acc
{
int id_no;
int pin;
float bal;
}Acc;
int Crte_acc()
{
FILE *flepss;
int i,cnt;
Acc user[10];
cnt = 1000;
flepss = fopen("Account.dat","wb");
for (i=1;i<10;i++)
{
cnt+=1;
user[i].id_no = cnt;
user[i].bal=10;
user[i].pin=0000;
fwrite(&user[i].id_no,sizeof(int),1,flepss);
fwrite(&user[i].pin,sizeof(int),1,flepss);
fwrite(&user[i].bal,sizeof(float),1,flepss);
}
return fclose(flepss);
}
void DisplyFile()
{
FILE *dfp;
int x;
Acc pruser[10];
dfp = fopen("Account.dat","rb");
fseek(dfp,0,SEEK_SET);
while (1)
{
if(!feof(dfp))
{
for (x=1;x<10;x++)
{
fread(&pruser[x].id_no,sizeof(pruser[x].id_no),1,dfp);
fread(&pruser[x].pin,sizeof(pruser[x].pin),1,dfp);
fread(&pruser[x].bal,sizeof(pruser[x].bal),1,dfp);
printf("%d ",pruser[x].id_no);
printf("%d ",pruser[x].pin);
printf("%.2f\n\n",pruser[x].bal);
}
}
else
{
break;
}
}
fclose(dfp);
}
int main()
{
Crte_acc();
printf("file printed\n");
DisplyFile();
printf("end file read 1\n");
DisplyFile();
printf("end file read 2\n");
return 0;
}
To compile : gcc main.c -o main
Bye,

libmp3lame encoding to char array slow

I am trying to encode pcm audio that i generated using "mplayer -ao pcm:nowaveheader" into mp3 with a c program. I don't want to write the mp3 to a file, I want to keep in in an array until i need to write it to a file, I wrote this, and it appears to work in a short .9 second test file, but it is very slow. What exactly is wrong?
#include <stdio.h>
#include <stdlib.h>
#include <lame/lame.h>
lame_global_flags *gfp;
int loopcount;
int inputSize;
FILE *fp=NULL;
FILE *fpo=NULL;
char *mp3buffer;
int mp3buffersize;
int countsize;
int x=0;
int y=0;
short *pcmbuffer;
short *lpcmbuffer;
short *rpcmbuffer;
int parse()
{
printf("loading PCM data...\n");
pcmbuffer=malloc(inputSize);
fread(pcmbuffer,2,(inputSize/2),fp);
printf("data in buffer\n");
printf("splitting left and right channels\n");
lpcmbuffer=malloc(inputSize/2);
countsize=((inputSize/4)-1);
while (x<=countsize)
{
lpcmbuffer[x]=pcmbuffer[x*2];
x++;
}
x=0;
rpcmbuffer=malloc(inputSize/2);
while (x<=countsize)
{
rpcmbuffer[x]=pcmbuffer[(x*2)+1];
x++;
}
x=0;
printf("starting lame\n");
gfp=lame_init();
lame_set_num_channels(gfp,2);
lame_set_in_samplerate(gfp,44100);
lame_set_brate(gfp,256);
lame_set_mode(gfp,1);
lame_set_quality(gfp,5);
if (lame_init_params(gfp)<0)
{
return 1;
}
}
encode()
{
x=0;
mp3buffersize=(1.25*countsize+7200);
mp3buffer=malloc(mp3buffersize);
while (x!=countsize)
{
lame_encode_buffer(gfp,lpcmbuffer,rpcmbuffer,x,mp3buffer,mp3buffersize);
x++;
y++;
if(y==1000)
{
printf("%d %d\n",countsize,x);
y=0;
}
}
x=0;
lame_encode_flush(gfp,mp3buffer,mp3buffersize);
fpo=fopen("test.mp3","w");
fwrite(mp3buffer,1,countsize,fpo);
}
decode()
{
}
bounty()
{
//the quicker picker upper
printf("closing files\n");
fclose(fpo);
fclose(fp);
printf("closing lame\n");
lame_close(gfp);
printf("freeing pcmbuffer\n");
free(pcmbuffer);
free(lpcmbuffer);
free(rpcmbuffer);
free(mp3buffer);
}
int main(int argc,char **argv)
{
loopcount=atoi(argv[1]);
fp=fopen(argv[2],"r");
if (fp==NULL)
{
printf("File Read Error\n");
return 0;
}
fseek(fp,0,SEEK_END);
inputSize=ftell(fp);
fseek(fp,0,SEEK_SET);
printf("detected a %d byte(s) file\n",inputSize);
printf("Proceeding with parsing and importing...\n");
if (parse()==1)
{
printf("lame init error\n");
}
printf("loopcount is %d\n",loopcount);
encode();
//the Quicker Picker Upper
bounty();
return 0;
}
Short answer, make this your encode function:
void encode()
{
mp3buffersize=(1.25*countsize+7200);
mp3buffer=malloc(mp3buffersize);
lame_encode_buffer(gfp, lpcmbuffer, rpcmbuffer, countsize, mp3buffer, mp3buffersize);
lame_encode_flush(gfp,mp3buffer,mp3buffersize);
fpo=fopen("test.mp3","w");
fwrite(mp3buffer,1,countsize,fpo);
}
I've never used lame, but, it looked like in your encode() function you were calling lame_encode_buffer() again and again, overwriting the result each time, and doing from 0 to countsize as the number of samples per channel (argument 4).
Other comments:
Why aren't you using lame_encode_buffer_interleaved()? Much of your parse() function is just undoing the existing interleaving of your file, seems like a waste.
IMO, the mass of global variables you're using are UGLY. Ideally your encode() would look more like: encode(lame_global_flags *gfp, const short * lpcmbuffer, const short * rpcmbuffer, const int countsize) this way it is clear from reading the parameter list the type of the variables, and that they must have come from/been set by the caller. const is nice to clarify that they're only for reading.
Finally, you really should have done some profiling, e.g. printing time differences between entry and exit of functions, to figure where your time sink was, and posted what you'd found. I ventured a guess looking at your loops, the encode() function had the only loop with any meat in it. I never ran your program, maybe I'm 100% wrong.

User entered string run a particular function in c

Guys so I'm working on the web service assignment and I have the server dishing out random stuff and reading the uri but now i want to have the server run a different function depending on what it reads in the uri. I understand that we can do this with function pointers but i'm not exactly sure how to read char* and assign it to a function pointer and have it invoke that function.
Example of what I'm trying to do: http://pastebin.com/FadCVH0h
I could use a switch statement i believe but wondering if there's a better way.
For such a thing, you will need a table that maps char * strings to function pointers. The program segfaults when you assign a function pointer to string because technically, a function pointer is not a string.
Note: the following program is for demonstration purpose only. No bounds checking is involved, and it contains hard-coded values and magic numbers
Now:
void print1()
{
printf("here");
}
void print2()
{
printf("Hello world");
}
struct Table {
char ptr[100];
void (*funcptr)(void)
}table[100] = {
{"here", print1},
{"hw", helloWorld}
};
int main(int argc, char *argv[])
{
int i = 0;
for(i = 0; i < 2; i++){
if(!strcmp(argv[1],table[i].ptr) { table[i].funcptr(); return 0;}
}
return 0;
}
I'm gonna give you a quite simple example, that I think, is useful to understand how good can be functions pointers in C. (If for example you would like to make a shell)
For example if you had a struct like this:
typedef struct s_function_pointer
{
char* cmp_string;
int (*function)(char* line);
} t_function_pointer;
Then, you could set up a t_function_pointer array which you'll browse:
int ls_function(char* line)
{
// do whatever you want with your ls function to parse line
return 0;
}
int echo_function(char* line)
{
// do whatever you want with your echo function to parse line
return 0;
}
void treat_input(t_function_pointer* functions, char* line)
{
int counter;
int builtin_size;
builtin_size = 0;
counter = 0;
while (functions[counter].cmp_string != NULL)
{
builtin_size = strlen(functions[counter].cmp_string);
if (strncmp(functions[counter].cmp_string, line, builtin_size) == 0)
{
if (functions[counter].function(line + builtin_size) < 0)
printf("An error has occured\n");
}
counter = counter + 1;
}
}
int main(void)
{
t_function_pointer functions[] = {{"ls", &ls_function},
{"echo", &echo_function},
{NULL, NULL}};
// Of course i'm not gonna do the input treatment part, but just guess it was here, and you'd call treat_input with each line you receive.
treat_input(functions, "ls -laR");
treat_input(functions, "echo helloworld");
return 0;
}
Hope this helps !

Resources