1

I've this struct:

struct _window{
int bcolor; /* background color */
int fcolor; /* foreground color */
int x; /* x coordinate */
int y; /* y coordinate */
int sx; /* lenght */
int sy; /* high*/
char **matrix; /* Matrix with chars */
};

I use this function to initialize the window

window* ini_window(int bcolor, int fcolor, int x, int y, int sx, int sy) {
window *v;
int i;

v = (window*) malloc(sizeof (window));
if (!v) /* CDE */
    return NULL;

v->bcolor = bcolor;
v->fcolor = fcolor;
v->x = x;
v->y = y;
v->sx = sx;
v->sy = sy;

/* allocate the matrix */
v->matrix = (char**) calloc(sy, sizeof (char*));
if (!v->matrix) { /* CDE */
    free(v);
    return NULL;
}

/* allocate the rows */
for (i = 0; i < sy; i++) {

    v->matrix[i] = (char*) calloc(sx + 1, sizeof (char));

    if (!v->matrix[i]) { /* CDE */
        free(v->matrix);
        free(v);
        return NULL;
    }

    v->matrix[i] = "\0"; /*<- delete this line to solve */
}
return v;

}

I try to load the matrix with that function

int cargar_matriz_file(window*v, char *nom_file) {
int i;
char aux[100];
FILE *pf;

if (!v)
    return -1;
if (!v->matrix)
    return -1;
pf = fopen(nom_file, "r");
if (!pf) /* CDE */
    return -1;



for (i = 0; i < v->sy; i++) {
    fgets(aux, v->sx, pf);
    if (v->matrix[i]) {
        strcpy(v->matrix[i], aux); /* <-segmentation fault here */
        strtok(v->matrix[i], "\r\n");
    }
}
fclose(pf);
return 0;
}

But there is an error in the line with the strcpy, aux have the correctly lenght and v->matrix[i] is allocated, what could be happening?

  • 2
    `v->matrix[i] = "\0";` rewrite value of malloc by address of string literal. – BLUEPIXY Nov 22 '15 at 11:41
  • I translated the code to post it, and i forgot change that line, it`s window, thanks, but that`s not the problem – Pablo Marcos Nov 22 '15 at 11:45
  • Thank you BLUEPIXY, that`s the problem – Pablo Marcos Nov 22 '15 at 11:47
  • Just a small note. Instead of doing a 2d array, you can directly do a 1d array and use a small formula to get the corresponding index. For example instead of a[row][col] you write a[row*rows+col]. This makes you save memory and keeps the entire structure contiguous in memory, – LtWorf Nov 22 '15 at 12:03
  • It's a good idea, I'll change it.Thanks LtWorf – Pablo Marcos Nov 22 '15 at 13:09

1 Answers1

4

To me it seems as if you first malloc to get some memory: v->matrix[i] = (char*) calloc(sx + 1, sizeof (char)); and then leak that memory by reassigning your pointer to a constant string: v->matrix[i] = "\0"; Writing to the contents of such a pointer will give a segfault.

You probably want to do something like sprintf or strcpy instead, or maybe just: v->matrix[i][0]=0;

Henrik Carlqvist
  • 1,138
  • 5
  • 6