I found a lot of similar questions concerning this error, but the answers I found did not help me.
My program works for eleven data points which I read from a list "data.dat" without errors. If I increase the number of data points I get this error I don't understand. The file with my data consists of three columns of float numbers.
Here is a short version of my code.
#define DIM 3
#include <stdlib.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
// Recursive function to build tree
void my_function(FILE* outFile, double* r, int* idxList, unsigned long int* Nodes, int *node, int n, unsigned long int myKey)
{
unsigned long int myKey1 = myKey;
for(int q=0; q<8; q++)
{
fprintf(outFile, "%d %d %d\n", q, n, *node);
myKey1 = (myKey << 3)|q;
Nodes[*node] = myKey1;
*node += 1;
if(*node < 20)
{
my_function(outFile, r, idxList, Nodes, node, n, myKey1);
}
}
}
int main(int argv, char** argc)
{
FILE *inFile;
inFile = fopen("data.dat", "r");
FILE *outFile;
outFile = fopen("result.dat", "w");
unsigned int n = 15; // Number of points
unsigned int N = n*DIM; // Elements in array
// Array for points
double *r = NULL;
r = (double*)malloc(sizeof(double)*N);
unsigned long int *Nodes = NULL;
Nodes = (unsigned long int*)malloc(sizeof(unsigned long int)*3*n);
for(int i=0; i<3*n; i++)
{
Nodes[i] = 0b0;
}
int *idxList = NULL;
idxList = (int*)malloc(sizeof(int)*3*n);
memset(idxList, -1, sizeof(int)*3*n); // Set all entries to -1
for(int k=0; k<N; k++)
{
fscanf(inFile, "%lf", &r[k]);
}
int node = 0;
unsigned long int myKey = 0b1;
my_function(outFile, r, idxList, treeNodes, &node, n, myKey);
// Close files
fclose(inFile);
fclose(outFile);
// Clean up
free(r);
free(Nodes);
free(idxList);
}
The program works, but if I put more data points to the list, I get the following error.
*** Error in `./myProgram': munmap_chunk(): invalid pointer: 0x0000000000f74810
Aborted (core dumped)
If I comment the section
// Close files
fclose(inFile);
fclose(outFile);
// Clean up
free(r);
free(Nodes);
free(idxList);
of my code, the error disappears. How can I fix this error? Any suggestions?
Related
As I was trying to write code which is supposed to sort some structures in a file by a specific field (key), I noticed that my function won't read the key correctly. I don't have any idea what I am doing wrong. The code is not complete.
The constr function is supposed to read one structure at a time from the binary file, then only save the varsta array. However, if I try to see what value I obtained, the values are not the ones I gave.
This is my code:
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
char nume[20];
char prenume[20];
float varsta;
} PERS;
typedef struct
{
float key;
int nr;
}INDEX;
int constr(FILE *f, INDEX tabl[])
{
int n;
n = ftell(f) / sizeof(PERS);
int i, depl = 0;
PERS p;
for (i = 0; i < n; i++)
{
fseek(f, depl, 0);
fread(&p, sizeof(p), 1, f);
tabl[i].key = p.varsta;
tabl[i].nr = i;
depl += sizeof(PERS);
}
return n;
}
int main()
{
FILE *f;
PERS pers[3];
if ((f = fopen("fis.txt", "wb+")) == NULL)
{
printf("Not ok");
exit(1);
}
int i;
for (i = 0; i < 3; i++)
{
scanf("%s%s%f", &pers[i].nume, &pers[i].prenume, &pers[i].varsta);
fwrite(&pers[i], sizeof(PERS), 1, f);
}
INDEX tabl[3];
int n = constr(f, tabl);
printf("%d", tabl[2].key); //only to check if the key is correct
fclose(f);
}
The key field is a float, but you are trying to print an integer.
Change the penultimate line in your code to
printf("%.2f\n", tabl[2].key);
i keep getting a segmentation fault when running this program. I'm attempting to read the files (inserted into the command line), and allocate the x and y coordinates in each file to a dynamically allocated memory struct called POINTS (using the function called readPoints). After they have been saved into these structs, i then pass them to the function calls calc where the x and y values are multiplied, and then added onto the next x and y multiplied.. so on. Could someone please explain to me where i went wrong! I am not great at pointers.
Thank you in advance.
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
float xcord;
float ycord;
}POINTS;
int readPoints(char* file, int numofpoints);
int calc(POINTS* points, int numofpoints);
int main(int argc, char* argv[])
{
int numoffiles;
FILE* file;
int result, i;
numoffiles = argc;
POINTS* pointer;
int numofpoints;
if(numoffiles == 1)
{
printf("Please enter a file\n");
}
for(i=1; i<numoffiles; i++)
{
file = fopen(argv[i], "r");
fscanf(file, "%d", &numofpoints);
pointer = readPoints(file, numofpoints);
if( pointer == NULL)
{
printf("Error return from readPoints function");
}
result = calc(&pointer[i], numoffiles);
printf("%12f", result);
free(pointer);
}
}
int readPoints(char* file,int numofpoints)
{
int i, j;
POINTS* Pointstructs;
Pointstructs = (POINTS*)malloc((numofpoints)*sizeof(POINTS));
if(file == NULL)
{
printf("Error transferring file into readPoints\n");
}
for(i=0; i<numofpoints; i++)
{
fscanf(*file, "%f, %f", &Pointstructs[i].xcord, &Pointstructs[i].ycord);
printf("%f, %f", Pointstructs[i].xcord, Pointstructs[i].ycord);
}
return Pointstructs;
}
int calc(POINTS* points, int numofpoints)
{
int i=0, j=0;
int answer;
while(i<numofpoints && j<numofpoints)
{
answer += points[i].xcord * points[j].ycord;
i++;
j++;
}
return answer;
}
readpoints functions should take its first argument as file pointer BCS fopen returns FILE pointer but u are using char pointer. fscanf first argument should be a file pointer. Pls correct it
I using first time the HEADERS in c so I'm not understanding it well.
main.c
#include <stdio.h>
#include <stdlib.h>
#include "kibe.h"
int main()
{
int a[5],n,i;
beolvas(a,n,"be.txt");
kiir(a,n);
return 0;
}
kibe.h
#ifndef KIBE_H_INCLUDED
#define KIBE_H_INCLUDED
void beolvas(int*, int, const char *);
void kiir(int*, int);
#endif // KIBE_H_INCLUDED
kibe.c
#include <stdio.h>
#include <stdlib.h>
void beolvas(int *a,int n,const char * file)
{
int i;
FILE * fin;
fin = fopen("be.txt", "rt");
fscanf(fin,"%i",&n);
a = (int*)malloc(n*sizeof(int));
for(i = 0; i < n; ++i){
fscanf(fin,"%i",&a[i]);
}
free(a);
}
void kiir(int *a,int n)
{
int i;
for(i = 0; i < n; ++i){
printf("%i ",a[i]);
}
}
The problem is that I get memory garbage every time and the file contains five numbers which must be read and written to monitor. If I write the void kiir is code to void beolvas function it works well.
You allocate dynamic memory in your function beolvas but you never pass it out of the function. Your parameters a and n have to be output parameters, so you have to change your function signature. Apart form this use fclos to close the file. Adapt your code like this:
kibe.c
void beolvas( int **a, int *n, const char * file )
// ^^ ^ output paramters a and n
{
FILE * fin;
fin = fopen("be.txt", "rt");
fscanf( fin, "%i", n ); // read number of elements
// ( n is a pointer to an int )
*a = malloc( *n * sizeof(int) ); // allocate memors
for ( int i = 0; i < n; ++i)
{
fscanf(fin,"%i",(*a)+i); // read one element
// ( *a is the pointer to the dynamic memory,
// so (*a)+i is a pointer to (*a)[i] )
}
fclose(fin);
}
kibe.h
void beolvas( int**, int* , const char *);
main.c
int main()
{
int a* = NULL;
int n = 0;
beolvas( &a, &n,"be.txt");
// ^ ^
kiir( a, n );
free(a); // free the memory which was allocated inside function beolvas
return 0;
}
I have an assignment where I need to get Values of RLC circuits from a file and calculate the resonant frequency however my issue is when I use the fscanf function it reads only the first line of the file and the rest comes out as zeros .
#include <stdio.h>
data
int h;
typedef struct cct
{
int code[50];
float R[50];
float L[50];
float C[50];
} CCT;
int read(CCT cct[], int n_p, FILE* fp){
char temp;
if(fp==NULL){
printf("Error\n");
return -1;
}
fscanf(fp,"%d,%f,%e,%e\n", cct[n_p].code, cct[n_p].R,cct[n_p].L, &cct[n_p].C);
}
int main()
{
FILE* fp = fopen("U://datafile.txt", "rt");
int i = 0;
CCT cct[50];
int size;
while (!feof(fp)) {
read(cct, i, fp);
i++;
}
size = i;
for (i = 0; i < size; ++i)
printf("%d,%0.2f,%0.2f,%0.2f\n", cct[i].code[i], cct[i].R[i],
cct[i].L[i], cct[i].C[i]);
scanf("%d",&h);
fclose(fp);
}
and this is the data file
1,4.36,2.23e-2,4.65e-8
2,4.57,2.01e-2,5.00e-8
3,3.99,2.46e-2,4.82e-8
4,4.09,2.60e-2,4.70e-8
I would appreciate if someone could point put why it only gets the first line. Thanks
CCT is composed of multiple arrays (you have arrays of arrays, which is wrong for the exercise, but that's not the point) and you always write to the element zero of the arrays. For example, cct[n_p].code in fscanf() is the address of the array, which is identical to the address of cct[n_p].code[0]. Then you print code[i] in the output loop, which is blank except for i == 0.
fscanf(fp,"%d,%f,%e,%e", cct[n_p].code, cct[n_p].R,cct[n_p].L, cct[n_p].C);
...
printf("%d,%0.2f,%0.2f,%0.2f\n", cct[i].code[0], cct[i].R[0], cct[i].L[0], cct[i].C[0]);
Something like the following, perhaps
#include <stdio.h>
typedef struct cct {
int code;
float R;
float L;
float C;
} CCT;
int h;
int read(CCT cct[], int n_p, FILE* fp){
char temp;
if(fp==NULL){
printf("Error\n");
return -1;
}
fscanf(fp,"%d,%f,%e,%e\n", &cct[n_p].code, &cct[n_p].R, &cct[n_p].L, &cct[n_p].C);
}
int main(){
FILE* fp = fopen("U://datafile.txt", "rt");
int i = 0;
CCT cct[50];
int size;
while (!feof(fp)) {
read(cct, i, fp);
i++;
}
size = i;
for (i = 0; i < size; ++i)
printf("%d,%0.2f,%0.2f,%0.2f\n", cct[i].code, cct[i].R, cct[i].L, cct[i].C);
scanf("%d",&h);
fclose(fp);
}
Hi I'm having trouble trying to initializing each element of the struct array. When I try and assign the value ZERO to both 'bSize' and 'msgs', it doesn't work as it errors out when i get to malloc. In the printf statement it prints a -1852803823 number. Excuse the messy code as i'm playing around trying to figure it out.
struct message{
int *data;
int bSize;
int msgs;
};
int main(int argc, char *argv[]) {
.....
}
void getSchedFile (FILE *file, int **schd) {
struct message sMsg[nodeCount];
const int pakSize = 6;
// Iniitialise message buffer
for (int i=0; i<nodeCount; i++){
sMsg[i].bSize = 0;
sMsg[i].msgs = 0;
printf("bSize %d\n",sMsg[i].bSize);
}
/* Get the number of bytes */
fseek(file, 0L, SEEK_SET);
int time;
while((fscanf(file, "%d", &time)) != EOF){
int src;
fscanf(file, "%d", &src); // get source node id
// These are here for easier reading code
int aPos = sMsg[src].bSize;
int nMsg = sMsg[src].msgs;
printf("size %d\n", sMsg[src].bSize);
if (sMsg[src].bSize==0){
sMsg[src].data = malloc( pakSize * sizeof(int));
}else{
sMsg[src].data = realloc(sMsg[src].data, (aPos+pakSize)*sizeof(int));
}
Where is the nodeCount value coming from? Is it a global variable? You should be very careful with global variables, and avoid using them if possible.
Pass the nodeCount in the method parameter and as Charlie mentioned, check it for > 0