pointer accurate pointer accurate - 18 days ago 5
C Question

What is wrong with this C program

I am trying to write a usb mass storage driver. I don't have a storage device, so I am trying to allocate some memory. below is the program I wrote to emulate
a 512*2048 (1 MB) size usb drive

#include <stdio.h>
#include <stdlib.h>


char ** called_func(char **mem, char start_sec, char num_of_sec)
{
char **read_mem, row, column;
read_mem = (char **)malloc(sizeof(char *) * 512 * num_of_sec);
for(row = 0 ; row < num_of_sec ; row++)
for(column = 0 ; column < 512 ; column++ )
read_mem[row][column] = mem[row + start_sec][column];

return read_mem;
}

int main()
{
char **mem, row , column, i, j;
char **ret;
mem = (char **)malloc(sizeof(char *) * 512 * 2048);

if(mem == NULL)
printf("allocation failed\n");
for(row = 0; row < 2048 ; row++)
for(column = 0 ; column < 512 ; column++)
mem[row][column] = 'a';


ret = called_func(mem, 2, 6);//start sec, num of sectors this time I am going to read from the second sector, and total 6 sectors
for(i=0;i<2;i++)
{
for(j=0;j<6;j++)
{
printf("ret[i][j] = %c",i, j, ret[i][j]);
}
printf("\n");
}
return 0;


}


I haven't wrote a C program in many months. Please tell where I am wrong as I keep getting segmentation fault.

Answer

The first problem is that you are not allocating memory for each char*. mem is a pointer to a pointer. This means this value will need allocation (as you do):

mem = (char **)malloc(sizeof(char*) * 2048);

You can remove the 512 from your code because this only needs memory for the pointers themselves not the actual characters in the pointers.

Then you need to malloc each individual char*. You could do this inside your for loop:

mem[row] = malloc(513);

This allocates memory for each char pointer. Keep in mind you need to add space for the null character at the end.

To free these you are going to need a loop similar to this:

for(row = 0; row < 2048; row++)
{
    mem[row];
}
free(mem);

That will get rid of the individual pointers and the double pointer.

This is enough to get you started but there are a few other issues with your code. I would recommend either using some type of debugger or simply adding print statements to watch what is happening with the code as it runs.

Comments