Segfault in my csv_loader() function - c

I'm trying to write a csv parser in C, but every time I get a segfault in this function. I don't know how to fix it.
char*** csv_loader(char *filename){
FILE* file_xx;
file_xx = fopen(filename, "r");
if(file_xx==NULL){
printf("Failed to open File, no such file or directory!\n");
return 0;
}
int c_=0;
int **linenumbers;
int l=lines(filename);
linenumbers=malloc(sizeof(int)*l);
char*** loaded_csv;
int counter_line=0;
int counter_row=0;
loaded_csv=malloc(sizeof(char **) *l);
loaded_csv[0][0]=malloc(getfirstcolumn(filename)*sizeof(char)+2);
if(NULL==loaded_csv){
printf("Failed to initialize 'char** loaded_csv'!\n");
return 0;
}
int c_c=0;
int *cm=get_column_map(filename);
for(c_c=0;c_c<l;c_c++){
loaded_csv[c_c]=malloc(sizeof(char *)*cm[c_c]);
}
while(c_!=EOF){
c_=getc(file_xx);
if(c_=='\n'){
linenumbers[counter_line][cm[counter_line]]=counter_row+2;
loaded_csv[counter_line][cm[counter_line]]=malloc(counter_row*sizeof(char));
if(NULL == loaded_csv[counter_line][cm[counter_line]]){
return 0;
}
loaded_csv[counter_line][counter_row]='\0';
counter_row=0;
counter_line++;
}else{
if(c_==','){
counter_row=0;
}else{
counter_row++;
}
}
}
fclose(file_xx);
FILE*fgetsread;
fgetsread=fopen(filename, "r");
int ident, ident_c;
for(ident=0;ident<l;ident++){
for(ident_c=0;ident_c<cm[ident];ident_c++){
fgets(loaded_csv[ident][ident_c], linenumbers[ident][ident_c], fgetsread);
loaded_csv[ident][ident_c][linenumbers[ident][ident_c]-2]='\0';
}
}
fclose(fgetsread);
free(linenumbers);
return loaded_csv;
}
The Debugger says it's this line:
loaded_csv[0][0]=malloc(getfirstcolumn(filename)*sizeof(char)+2);
Does anyone know what's the bug? I'm yet new to C and anyway try to understand the malloc thing...
PS: the other functions are here: http://pastebin.com/VQZ4d5UU

So, you've allocated space on the line right before:
loaded_csv=malloc(sizeof(char **) *l);
That is fine and dandy, but loaded_csv[0] isn't yet initialized to somewhere you own. So, when you do the following line
loaded_csv[0][0]=malloc(getfirstcolumn(filename)*sizeof(char)+2);
you are trying to set a variable located in some random location (wherever loaded_csv[0] happens to be right then).
If you want to touch loaded_csv[0][0], you'll have to make sure that loaded_csv[0] is pointing to valid memory first (probably by allocating memory for it via malloc before you allocate something for loaded_csv[0][0].)

You've got a problem with this line:
loaded_csv[0][0]=malloc(getfirstcolumn(filename)*sizeof(char)+2);
Which suggest you are not allocating and initializing loaded_csv[0][0] right.
Here is an example of how to initialize and use a char ***var:
#include <windows.h>
#include <ansi_c.h>
char *** Create3D(int p, int c, int r);
int main(void)
{
char ***pppVar;
pppVar = Create3D(10,10,10);
//test pppVar;
strcpy(pppVar[0][0], "asdfasf");
strcpy(pppVar[0][1], "the ball");
return 0;
}
char *** Create3D(int p, int c, int r)
{
char *space;
char ***arr;
int x,y;
space = calloc (p*c*r*sizeof(char),sizeof(char));
arr = calloc(p * sizeof(char **), sizeof(char));
for(x = 0; x < p; x++)
{
arr[x] = calloc(c * sizeof(char *),sizeof(char));
for(y = 0; y < c; y++)
{
arr[x][y] = ((char *)space + (x*(c*r) + y*r));
}
}
return arr;
}
Be sure to keep track of and free(x) appropriately.

Related

Using an array of structures with call by reference

Here is my problem: I have to make this program for school and I spent the last hour debugging and googling and haven't found an answer.
I have an array of structures in my main and I want to give that array to my function seteverythingup (by call by reference) because in this function a string I read from a file is split up, and I want to write it into the structure but I always get a SIGSEV error when strcpy with the struct array.
This is my main:
int main(int argc, char *argv[])
{
FILE* datei;
int size = 10;
int used = 0;
char line[1000];
struct raeume *arr = (raeume *) malloc(size * sizeof(raeume*));
if(arr == NULL){
return 0;
}
if(argc < 2){
return 0;
}
datei = fopen(argv[1], "rt");
if(datei == NULL){
return 0;
}
fgets(line,sizeof(line),datei);
while(fgets(line,sizeof(line),datei)){
int l = strlen(line);
if(line[l-1] == '\n'){
line[l-1] = '\0';
}
seteverythingup(&line,arr,size,&used);
}
ausgabeunsortiert(arr,size);
fclose(datei);
return 0;
}
and this is my function:
void seteverythingup(char line[],struct raeume *arr[], int size,int used)
{
char *token,raumnummer[5],klasse[6];
int tische = 0;
const char c[2] = ";";
int i=0;
token = strtok(line, c);
strcpy(raumnummer,token);
while(token != NULL )
{
token = strtok(NULL, c);
if(i==0){
strcpy(klasse,token);
}else if(i==1){
sscanf(token,"%d",&tische);
}
i++;
}
managesize(&arr[size],&size,used);
strcpy(arr[used]->number,raumnummer);
strcpy(arr[used]->klasse,klasse);
arr[used]->tische = tische;
used++;
}
Edit: Since there is more confusion I wrote a short program that works out the part you are having trouble with.
#include <cstdlib>
struct raeume {
int foo;
int bar;
};
void seteverythingup(struct raeume *arr, size_t len) {
for (size_t i = 0; i < len; ++i) {
arr[i].foo = 42;
arr[i].bar = 53;
}
}
int main() {
const size_t size = 10;
struct raeume *arr = (struct raeume*) malloc(size * sizeof(struct raeume));
seteverythingup(arr, size);
return 0;
}
So basically the signature of your functions is somewhat odd. Malloc returns you a pointer to a memory location. So you really dont need a pointer to an array. Just pass the function the pointer you got from malloc and the function will be able to manipulate that region.
Original Answer:
malloc(size * sizeof(raeume*));
This is probably the part of the code that gives you a hard time. sizeof returns the size of a type. You ask sizeof how many bytes a pointer to you raeume struct requires. what you probably wanted to do is ask for the size of the struct itself and allocate size times space for that. So the correct call to malloc would be:
malloc(size * sizeof(struct raeume));

Segmentation fault after while loop that follows malloc

I am trying to create a 2d array dynamically, then open a txt file and copy each lenient my 2d array. Then save this array back to my main. I keep running into a segmentation error. Any suggestions how to do fix this code?
BTW i think the problem stars after the 2nd time while loop occurs...
#include<stdio.h>
char **randomArrayofStrings(){
char **twoArray=null;
int rows=50;
int col=20;
i=0;
FILE *file=null;
int messageSize=50;//this is number is trivial
file = fopen("somefile.txt","r");
twoArray= malloc(rows*sizeof(char*));
for(i=0;i<col;i++)
{
twoArray[i]=malloc(rows*sizeof(char));
strcpy(twoArray[i], "some random word");
}
while(!feof(file))
{
fgets(dArray[i],messageSize, file);
strtok(dArray[i], "\n");
i++;
}
return twoArray;
}
int main(int argc, char **argv)
{
char **localArray=null;
localArray=randomArrayofStrings();
for(i=0;i<20;i++)//20 is just a random number
printf("Strings: %s", localArray[i]);
}
As I see, in your function randomArrayofStrings loop for goes through columns "i cols in your code. So, you allocate array of pointers first and consider it as cols and then in a loop you allocate rows.
And after malloc check the value that was returned and do not use the pointer if it is NULL after memory allocation.
To free allocated memory, use the inverted sequence - free all rows in a loop and than free cols once. E.g.:
for(i=0;i<col;i++){
free(twoArray[i]);
}
free(twoArray);
twoArray = NULL;
EDIT:
And also, to use malloc and free you need #include <stdlib.h>, and #include <string.h> for strcopy, int i=0; should be instead of i=0;, and correct null value for pointers is NULL.
And what is dArray? I do not see the declaration or definition? Dou you mean twoArray?
EDIT2:
The following is my version of your program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **randomArrayofStrings(){
char **twoArray=NULL;
char * ptr = NULL;
int rows=50; // this will be also message size
int cols=20;
int i=0;
FILE *file=NULL;
file = fopen("somefile.txt","r");
if( file == NULL )
return NULL;
twoArray = (char**) malloc(cols * sizeof(char*));
if(twoArray == NULL)
{
return NULL;
}
for(i=0;i<cols;i++)
{
twoArray[i] = (char*)malloc(rows*sizeof(char));
if(twoArray[i] == NULL)
return NULL;
strcpy(twoArray[i], "some random word");
}
i = 0; // reset counter
while(!feof(file))
{
fgets(twoArray[i], rows, file);
ptr = strchr(twoArray[i],'\n');
if( ptr )
*ptr = '\0';
else
twoArray[i][rows-1] = '\0';
i++;
if( i >= cols)
break;
}
fclose(file);
return twoArray;
}
void freeMy2dArray(char **twoArray, int n)
{
int i;
for(i=0; i < n; i++){
free(twoArray[i]);
}
free(twoArray);
twoArray = NULL;
}
int main(int argc, char **argv)
{
int i;
char **localArray=NULL;
localArray = randomArrayofStrings();
if( localArray == NULL )
return 1;
for(i=0;i<20;i++)//20 is just a random number
printf("Strings: %s\n", localArray[i]);
freeMy2dArray(localArray, 20);
}
You are not suppossed to free() twoArray inside randomArrayofStrings(). You have to free them inside main(), once you're done with using the allocated memeory.
That said, the way you're using sizeof(localArray) in main() is wrong. You have to use the exact value you did use to poupulate twoArray.

Passing pointer of pointers to function, returning both an int and an address (by parameter)

I've got a function which, as is, works correctly. However the rest of the program has a limitation in that I've preset the size of the array (the space to be allocated). Obviously, this is problematic should an event arise in which I need extra space for that array. So I want to add dynamic allocation of memory into my program.
But I'm having an issue with the whole pointer to a pointer concept, and I've utterly failed to find an online explanation that makes sense to me...
I think I'll want to use malloc(iRead + 1) to get an array of the right size, but I'm not sure what that should be assigned to... *array? **array? I'm not at all sure.
And I'm also not clear on my while loops. &array[iRead] will no longer work, and I'm not sure how to get a hold of the elements in the array when there's a pointer to a pointer involved.
Can anyone point (heh pointer pun) me in the right direction?
I can think of the following approaches.
First approach
Make two passes through the file.
In the first pass, read the numbers and discard them but keep counting the number of items.
Allocate memory once for all the items.
Rewind the file and make a second pass through it. In the second pass, read and store the numbers.
int getNumberOfItems(FILE* fp, int hexi)
{
int numItems = 0;
int number;
char const* format = (hexi == 0) ? "%X" : "%d";
while (fscanf(fp, format, &number) > 0) {
++numItems;
return numItems;
}
void read(int *array, FILE* fp, int numItems, int hexi)
{
int i = 0;
char const* format = (hexi == 0) ? "%X" : "%d";
for ( i = 0; i < numItems; ++i )
fscanf(fp, format, &array[i]);
}
int main(int argc, char** argv)
{
int hexi = 0;
FILE* fp = fopen(argv[1], "r");
// if ( fp == NULL )
// Add error checking code
// Get the number of items in the file.
int numItems = getNumberOfItems(fp, hexi);
// Allocate memory for the items.
int* array = malloc(sizeof(int)*numItems);
// Rewind the file before reading the data
frewind(fp);
// Read the data.
read(array, fp, numItems, hexi);
// Use the data
// ...
// ...
// Dealloate memory
free(array);
}
Second approach.
Keep reading numbers from the file.
Every time you read a number, use realloc to allocate space the additional item.
Store the in the reallocated memory.
int read(int **array, char* fpin, int hexi)
{
int number;
int iRead = 0;
// Local variable for ease of use.
int* arr = NULL;
char const* format = (hexi == 0) ? "%X" : "%d";
FILE *fp = fopen(fpin, "r");
if (NULL == fp){
printf("File open error!\n");
exit(-1);
}
while (fscanf(fp, format, &number) > 0) {
arr = realloc(arr, sizeof(int)*(iRead+1));
arr[iRead] = number;
iRead += 1;
}
fclose(fp);
// Return the array in the output argument.
*array = arr;
return iRead;
}
int main(int argc, char** argv)
{
int hexi = 0;
int* array = NULL;
// Read the data.
int numItems = read(&array, argv[1], hexi);
// Use the data
// ...
// ...
// Dealloate memory
free(array);
}
int read(int **array, char* fpin, int hexi) {
int iRead = 0;
int i, *ary;
char *para;
FILE *fp;
fp = fopen(fpin, "r");
if (NULL == fp){
printf("File open error!\n");
exit(-1);
}
para = (hexi == 0) ? "%*X" : "%*d";
while (fscanf(fp, para)!= EOF)
++iRead;
ary = *array = malloc(iRead*sizeof(int));
if(ary == NULL){
printf("malloc error!\n");
exit(-2);
}
rewind(fp);
para = (hexi == 0) ? "%X" : "%d";
for(i = 0; i < iRead; ++i)
fscanf(fp, para, &ary[i]);
fclose(fp);
return iRead;
}
I'd suggest something like this:
int read(int **array_pp, char* fpin, int hexi) {
...
int *array = malloc (sizeof (int) * n);
for (int i=0; i < n; i++)
fscanf(fp, "%X",&array[i]);
...
*array_pp = array;
return n;
}
Notes:
1) You must use "**" if you want to return a pointer in a function argument
2) If you prefer, however, you can declare two pointer variables (array_pp and array) to simplify your code.
I think you wouldn't call it an array. Arrays are of fixed size and lie on the stack. What you need (as you already said), is dynamically allocated memory on the heap.
maybe that's why you didn't find much :)
here are some tutorials:
http://en.wikibooks.org/wiki/C_Programming/Arrays (and following pages)
http://www.eskimo.com/~scs/cclass/int/sx8.html
you got the function declaration correctly:
int read(int **array, char* fpin, int hexi)
What you need to do:
find out how much memory you need, eg. how many elements
allocate it with *array = malloc(numElements * sizeof(int)) (read "at the address pointed by array allocate memory for numElements ints")
now you can (*array)[idx] = some int (read "at the address pointed by array, take the element with index idx and assign some int to it")
call it with int* destination; int size = read(&destination, "asdf", hexi)
hope it helps..

Memory allocation of 3-d arrays for reading pixel data of images using libjpeg

I am trying to copy the pixel data of an image to a matrix using libjpeg. Something is going wrong with the pointers. Please help.
The problem in brief: I pass an int ***p pointer to a function which reads pixel data. Within the function, I am able to access the elements p[i][j][k] and perform operations on them but when I try to do the same in main the program crashes.
The main function is:
#include<stdio.h>
#include<stdlib.h>
#include<jpeglib.h>
#include"functions.h"
void main(void)
{
char * file="a.jpg";
int ***p; // to store the pixel values
int s[2]={0,0}; // to store the dimensions of the image
read_JPEG_file(file,p,s); // Function that reads the image
printf("%d",p[0][0][0]); // This makes the program crash
}
The file functions.h reads:
int read_JPEG_file(char * file, int ***p, int **s)
{
int i,j;
//-----------------libjpeg procedure which I got from the documentation------------
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
cinfo.err=jpeg_std_error(&jerr);
FILE * infile; /* source file */
JSAMPARRAY buffer; /* Output row buffer */
int row_stride;
if ((infile = fopen(filename, "rb")) == NULL)
{
fprintf(stderr, "can't open %s\n", filename);
return 0;
}
jpeg_create_decompress(&cinfo);
jpeg_stdio_src(&cinfo, infile);
jpeg_read_header(&cinfo, TRUE);
jpeg_start_decompress(&cinfo);
row_stride = cinfo.output_width * cinfo.output_components;
buffer=(*cinfo.mem->alloc_sarray)((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
s[0]=cinfo.output_height;
s[1]=cinfo.output_width;
p=(int ***)malloc(s[0]*sizeof(int **));
for (i=0;i<s[0];i++)
{
p[i]=(int **)malloc(s[1]*sizeof(int *));
for (j=0;j<s[1];j++)
{
p[i][j]=(int *)malloc(3*sizeof(int));
}
}
while (cinfo.output_scanline < cinfo.output_height)
{
jpeg_read_scanlines(&cinfo, buffer, 1);
for ( i=0; i<cinfo.output_width; i++)
{
p[cinfo.output_scanline-1][i][0]=(int)buffer[0][0+3*i];
p[cinfo.output_scanline-1][i][1]=(int)buffer[0][1+3*i];
p[cinfo.output_scanline-1][i][2]=(int)buffer[0][2+3*i];
}
}
printf("%d",p[0][0][0]); // This works just fine
return 0;
}
I know that something is wrong with the memory allocation but I don't know what. I tried another test program and successfully allocated a memory block 500X500X500 integers long, and it was working-it was outputting random integers without crashing- so lack of memory is not a problem.
Your int ***p isn't malloc.
When you send him to read_JPEG_file a second variable int ***p was created.
This second variable was destruct at the end of read_JPEG_file. So you can use p
in read_JPEG_file but that's all.
There is three way to solve it.
The first and I think the easier to understand is to return p.
int ***read_JPEG_file(char * file, int ***p, int **s) {
...
return p;
}
int main() {
...
p = read_JPEG_file(file, p, s);
}
(It became unnecessary to send p)
The second way is to malloc p in the main and then to send him.
It seems a bit hard to do in your case.
The third is to send the address of p in the main. You will have a (int * * * *p).
You have to take care when you use it.
You can do something like that :
int read_JPEG_file(char * file, int ****p, int **s)
{
...
*p=(int ***)malloc(s[0]*sizeof(int **));
}
Now you have to use *p instead of p.
*p mean the value that contain the pointer p. p is an int * * * * so his value is the int * * *.
int main()
{
...
read_JPEG_file(file, &p, s);
}

attempt to free memory causes error

I have declared the following struct:
typedef struct _RECOGNITIONRESULT {
int begin_time_ms, end_time_ms;
char* word;
} RECOGNITIONRESULT;
There is a method that creates an array of RECOGNITIONRESULT and fills it (for test purposes only):
void test_realloc(RECOGNITIONRESULT** p, int count){
int i;
*p = (RECOGNITIONRESULT *)realloc(*p, count * sizeof(RECOGNITIONRESULT));
for (i = 0; i < count; i++){
(*p)[i].begin_time_ms = 2*i;
(*p)[i].end_time_ms = 2*i+1;
(*p)[i].word=(char *) malloc ( (strlen("hello"+1) * sizeof(char ) ));
strcpy((*p)[i].word,"hello");
}
}
The method to free memory is:
void free_realloc(RECOGNITIONRESULT* p, int count){
int i = 0;
if(p != NULL){
if (count > 0){
for (i = 0; i < count; i++){
free(p[i].word); //THE PROBLEM IS HERE.
}
}
free(p);
}
}
The main method calls those methods like this:
int main(int argc, char** argv)
{
int count = 10;
RECOGNITIONRESULT *p = NULL;
test_realloc(&p,count);
free_realloc(p,count);
return 0;
}
Then if I try to free the memory allocated for "word", I get the following error:
HEAP CORRUPTION DETECTED: after normal block (#63) at 0x003D31D8.
CRT detected that the application wrote to memory after end of heap buffer.
Using the debugger I've discovered that the crash occurs when calling free(p[i].word);
What am I doing wrong? How can I free he memory for the strings?
The problem is in your allocation of memory for word. strlen("hello"+1) should be strlen("hello")+1.
Since you appear to allocate a whole array of structures in one strike
RECOGNITIONRESULT **p;
*p = (RECOGNITIONRESULT *)realloc(*p, count * sizeof(RECOGNITIONRESULT));
you can free them in one call to free() as well :
void free_realloc(RECOGNITIONRESULT *p, int count){
free(p);
}
And the strlen("hello"+1) is also wrong, as detected by Chowlett.

Resources