May 31, 2011 at 9:13pm UTC
Hi guys, I'm trying to load an image into a buffer, but it gives a segmentation fault. Here's the code
main:
1 2 3 4 5 6 7 8 9 10
#include "imagen.h"
#include "codificar.h"
#include "imagenES.h"
using namespace std;
int main (int argc, char ** argv) {
Imagen test(512,512);
test.leerimagen(argv[1]);
}
class private
1 2 3
private :
int fil,col;
unsigned char **buffer;
Constructor:
1 2 3 4 5 6 7
Imagen::Imagen(int filas,int columnas) {
fil=filas;
col=columnas;
buffer=new unsigned char *[fil];
for (int i=0; i<fil; i++)
buffer[i]=new unsigned char [col];
}
reading image
1 2 3 4
bool Imagen::leerimagen(const char file[]){ // se puede saber con antelacion fil y col???
return LeerImagenPGM(file,fil,col,*buffer);
}
function of reading an image
1 2 3 4 5 6 7 8 9 10 11 12 13 14
bool LeerImagenPGM (const char nombre[], int & filas, int & columnas, unsigned char buffer[])
{
bool exito= false ;
filas=0;
columnas=0;
ifstream f(nombre);
if (LeerTipo(f)==IMG_PGM)
if (LeerCabecera (f, filas, columnas))
if (f.read(reinterpret_cast <char *>(buffer),filas*columnas))
exito= true ;
return exito;
}
I am sure that LeerImagenPGM is working ok (actually it is not I who did that function so that's why I am positive that's not the function that gives the segfault, lol).
The image IS actually 512 x 512.
Last edited on May 31, 2011 at 9:14pm UTC
Jun 1, 2011 at 12:10am UTC
The buffer is wrong. It should be:
unsigned char *buffer = new unsigned char [fil * col];
Jun 1, 2011 at 11:28am UTC
The buffer must be a matrix. It is a requirement. and must be done that way (pointer to pointers).
Jun 1, 2011 at 11:45am UTC
Compile it with debugging symbols in, run it under a debugger, and know exactly on which line and with what values the segFault occurs.
Last edited on Jun 1, 2011 at 11:46am UTC
Jun 1, 2011 at 12:27pm UTC
As ye
sow new, so shall ye
reap delete.
Something like this, possibly. I don't often allocate arrays of pointers to arrays, so I could well have this a bit wrong.
1 2 3 4 5 6 7 8 9 10 11 12 13
// Allocate
buffer=new unsigned char *[fil];
for (int i=0; i<fil; i++)
buffer[i]=new unsigned char [col];
.
.
.
.
// deallocate
for (int i=0; i<fil; i++)
delete [] buffer[i];
delete [] buffer;
Alternatively, use a C++ container such as vector and you won't have to worry about it :)
Last edited on Jun 1, 2011 at 12:34pm UTC
Jun 1, 2011 at 1:04pm UTC
Yes, that was a bit of a hacked together stab in the dark at it!
If you don't want to use vectors, you might find it easier you to use a single array of size fil*col to store all the pixels. It'll be much simpler to allocate, deallocate and use.