in the following code, I am trying to make a function makestudernts(). it takes in a string and makes the objects puts it into the array and returns it.
however, I'm getting the following error
a.out: malloc.c:2374: sysmalloc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct mallo c_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+( (2 *(sizeof(size_t))) - 1)) & ~((2 *(sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long) old_end & pagemask) == 0)' failed. Aborted (core dumped)
the only thing I was able to figure out was that String str3 = malloc(sizeof(char)*i); was the line that causes it.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef char* String; void stringMalloc(String str, int size); String fileToString(FILE * file); void freeString(String str); struct Point2D{ double x; double y; }; struct busRote{ struct Point2D * point; String name; }; struct Student{ struct Point2D point; String name; struct busRote rote; int stop; }; void setPoint(struct Point2D * i , double x, double y){ (*i).x =x; (*i).y = y; } void* makestudernts(String str){ String str1 = str; String str2 = strchr(str1, ' ' ); int count = 0; while(strchr(str1, '\n') != NULL){ count++; str1 = strchr(str1, '\n') +1; } struct Student * arr = malloc( sizeof(struct Student*) * count); str1 = str; str2 = strchr(str1, ' ' ); for(int j = 0; j < count; j++){ double x = strtod(str1, &str2); str1 = str2; str2 = strchr(str1, ' ' ); double y = strtod(str1, &str2); str1 = str2; int i = 0; i = 5; i = strlen(str2); if( (strchr(str2, '\n') - str2) < i ){ i= strchr(str2, '\n') - str2; } str2 = strchr(str2, '\n'); String str3 = malloc(sizeof(char)*i); strncpy(str3, str1, i); str1 = str2; struct Point2D point; setPoint(&point, x,y); struct Student student; student.point = point; student.name = str3; arr[j] = student; }printf("%s", arr[0].name); return arr; } int main(int argi, String argv[]){ if(argi <3){ printf("not enof files"); }else{ FILE* studentFile; FILE* busFile; studentFile = fopen (argv[1], "r"); busFile = fopen (argv[2], "r"); if (studentFile == NULL || busFile == NULL){ printf("files not found"); }else{ String studentString; String busString; studentString = fileToString(studentFile); busString = fileToString(busFile); struct Student * arr= makestudernts(studentString); freeString(studentString); freeString(busString); fclose(studentFile); fclose(busFile); } } } String fileToString(FILE * file){ char ch = fgetc( file ); int count = 0; while(ch != EOF){ count++; ch = fgetc(file); } String string = malloc(sizeof(char) * count); rewind(file); for(int i = 0; i < count; i++){ string[i] = fgetc(file); } return string; } void freeString(String str){ free(str); }
mainfunction and everything else needed to compile and run the code without having to guess what to fill in.