Program stops when defining large dynamic 2D array in C [closed] - c

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am trying to define two dynamic 2-dimensional arrays using malloc and here is the code (I know that M = 118 and N = 186):
int **Cf;
Cf = (int **) malloc(M * sizeof(int *));
for (i = 0; i < N; i++)
Cf[i] = (int *) malloc(N * sizeof(int));
The array Cf allocates memory with no problem. However, my program crashes when it comes to Ct. I debugged the code and found out that Ct[i] = (int *) malloc(N * sizeof(int)) fails when N=164 which is kinda weird.

Key issue: Wrong range used. Should be <M, not <N. #xing
Recommend using sizeof against the referenced object than the type. Easier to code, review and maintain.
Note that the casts are not required. #Some programmer dude
int **Cf = malloc(sizeof *CF * M);
assert(Cf);
// M, not N
// for(i=0;i<N;i++){
for(size_t m=0; m < M; m++){
printf("%zu\n", m);
Cf[m] = malloc(sizeof *(Cf[m]) * N);
assert(Cf[m]);
}
Code also used m instead of i to help make clear that the m index goes with M.
To use calloc()
// int **Cf = malloc(sizeof *CF * M);
int **Cf = calloc(M, sizeof *CF);
// Cf[m] = malloc(sizeof *(Cf[m]) * N);
Cf[m] = calloc(N, sizeof *(Cf[m]));

Related

How can you dynamically allocate a pointer in the form int (*p)[n] in C? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Suppose I get input from somewhere and store it in a variable. Pretend the variable is Cols.
I want to make an array in the form
int (*p)[Cols]
Now, I know you can't do this. So how would I dynamically allocate it to do it?
Teaching me how to do so would really be appreciated!
You can absolutely use int (*p)[Cols], it's a pointer to array of size Cols (Cols times size of int, in bytes), you just have to allocate memory for it, until you do, it doesn't point to a valid memory location. The constraint is that the allocated memory needs to be in blocks of multiples of Cols:
int (*p)[Cols] = malloc(sizeof *p); //prefered
Or
int (*p)[Cols] = malloc(sizeof(int) * Cols); //alternative
In both of the above expressions, supposing Cols's value is 10, p will point to a block of memory that can take 10 ints.
Usage:
for (int i = 0; i < Cols; i++)
{
p[0][i] = i;
}
The above expresssions only allocated space for one line of ints, but since p is a pointer to array, you can allocate space for as many of them as you want (given the memory constraints).
Let's assume you want an array with 5 lines and Cols columns:
int (*p)[Cols] = malloc(sizeof *p * 5);
Usage:
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < Cols; j++)
{
p[i][j] = i * j;
}
}
As you (probably) know this kind of construct is primarily used to emulate a 2D array, one of the advantages is that you can then free all the memory with a single free:
free(p);
Whereas constructs like an array of pointers, or a pointer to pointer would force you have multiple frees.
int (*p)[Cols] = malloc( sizeof *p * Rows );
allocates enough space for a Rows x Cols array of int and assigns the address of that array to p. You can then access each element as p[i][j].
To deallocate all you need is
free( p );

Segmentation fault when initializing 2D array in c [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am declaring a 2d array in a headers file like this : int **arr;
Then I'm allocating memory and I initialize it with zeros.
However I'm getting segmentation fault.
Here is my code :
arr = (int **)malloc(d * sizeof(int *));
for (int u=0; u<d; u++)
arr[u] = (int *)malloc(q * sizeof(int));
for(int i=0; i<d+1; i++)
{
for(int j=0; j<q+1; j++)
{
arr[i][j]=0;
}
}
d+1 and q+1 both outside the boundary.
Use d and q
If you want to initialize with zero use calloc() which is simple to use and reduces redundant operations
arr = (int **)malloc(d * sizeof(int *));
for (int u=0; u<d; u++)
scoreBoard[u] = (int *)calloc(q , sizeof(int));
This code will create 2d int array and initialize with zero
You are getting a segmentation fault because you are overstepping the array's bounds.
for (int i = 0; i < d + 1; i++)
Should become:
for (int i = 0; i < d; i++)
And similarly for the other one. Don't forget array indices go from 0 to 1 less than the size (in elements) of the array.
Also:
Was the memory for scoreboard allocated? Currently, you create an array called arr rather than for the scoreboard you are initializing, so scoreboard[u] may also be out of bounds regardless of the value of u.

Define a very large 2D array array with double type [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to define a 2D array with size 20*100000 in C. I do not want to keep the size fixed.
double **twod = malloc(20 * sizeof(double *));
int i;
if (twod == NULL)
abort();
for (i = 0; i < 20; ++i)
if ((twod[i] = malloc(100000 * sizeof(double))) == NULL)
abort();
// clean up
for (i = 0; i < 20; ++i)
free(twod[i]);
free(twod);
The first malloc call allocates space for 20 double pointers. Each double pointer will point to a subarray.
The second malloc call in the loop allocates 100000 doubles in each subarray.
The free calls do the inverse of malloc--they return memory to free store. First, each subarray must be freed, in a loop. Then the entire array itself must be freed too.
The return value of malloc is examined against NULL. If malloc returns NULL, then the system is out of memory. This is important since you are allocating HUGE amounts of memory. If malloc returns NULL, the application is aborted.
You'll need to define a pointer to pointer and initialize it like this:
int i;
double **array;
array = malloc(sizeof(double *)) * 20);
for (i=0; i<20; i++) {
array[i] = malloc(sizeof(double) * 100000);
}
Don't forget to free the memory when you're done with it.
You can use a Variable-length array (since C99) in order to avoid fragmentation:
double (*array)[cols];
array = malloc(sizeof(*array) * rows);
In this way calling free(array); is enough.

segmentation fault while accessing an array element's [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
here is my problem, I malloc my array like that:
e->map = malloc(sizeof(int *) * e->map_y);
i = -1;
while (++i < e->map_x)
e->map[i] = malloc(sizeof(int) * e->map_x);
where e->map_y = 14 and e->map_x = 10
The problem is I can't access (I have a segfault) elements after e->map[10][0] (included)
I tough about I invert x and y but it doesn't seem to be the case here.
I can post my entire code if necessary, thx
hi, I added the entire project on github for more details: https://github.com/42-hbock/fdf
this part of the code is in src/default_reading.c, the malloc is in the function char *default_reading(char *file, t_env *e) and I have the segmentation fault while accessing in void create_int_map(char *cmap, t_env *e)
Should be:
e->map = malloc(sizeof(int *) * e->map_y);
i = -1;
while (++i < e->map_y)
e->map[i] = malloc(sizeof(int) * e->map_x);
The change is having the while look at e->map_y instead of e->map_x. The rest of the code is the same.

Segmentation fault while trying to make a Matrix in C [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
well, i'm working in C. I want to make a function that return a matrix[][].
This is my function:
char **mapa(int largo,int ancho)
{
char **matriz;
int i,j;
matriz = (char **)malloc(sizeof(char)*largo);
for(i = 0; i < largo; ++i)
{
matriz[i]= (char *)malloc(sizeof(char)*ancho);
}
for(i = 0; i < largo; i++)
{
for(j = 0; j < ancho; j++)
{
matriz[i][j] = 'k';
}
}
for(i = 0; i < largo; i++)
{
for (j = 0; j < ancho; j++)
{
printf("%c",matriz[i][j]);
}
}
return matriz;
}
Using gdb it give me this:
Program received signal SIGSEGV, Segmentation fault.
0x00000000004008b8 in mapa (largo=10, ancho=10) at main.c:18
18 matriz[i][j] = 'k';
I don't know where the error is, if someone can give me a hand i'll be very gratefull.
Many thanks.
char **matriz;
int i,j;
matriz = (char **)malloc(sizeof(char)*largo);
Your matriz variable is a pointer to an array of pointers, each of which points to an array of char. You first need to allocate memory for the array of pointers, which requires largo times the size of the pointers, which is sizeof (char *). You only allocate space for largo times the size of a single char.
The easiest way to get the allocation right is to use the following pattern:
p = malloc (n * sizeof *p);
In other words, allocate n times the size of whatever p points to. This will automatically allocate the right amount regardless of the type of p, assuming you get the n right. If you're declaring the pointer in the same line, it looks a little different:
T *p = malloc (n * sizeof *p); /* For some type T */
In this case there is an asterisk before p on both sides. This difference is something you will have to be aware of, especially when you have more than one level of indirection.
Your first allocation, using this pattern, would look like this:
matriz = malloc (largo * sizeof *matriz);
and the second:
matriz[i] = malloc (ancho * sizeof *matriz[i]);
Note, that you never have to cast a void pointer (the return value of malloc()), and that the argument to the sizeof operator only needs parenthesis when it's a type name. When you get rid of the parenthesis, and place the quantity (ancho) before the sizeof operator, the result is an expression that is very clean and easy to understand. That is, of course, my personal opinion.
Your first malloc casts to a pointer of pointer's but that doesn't mean it is. If you look at your 2nd malloc you're allocating the same thing. So when you dereference matriz[i][z] you're dereferencing a charater, not a pointer. So I believe, it's been a while since I've done C, your first malloc needs to be (char**)malloc(sizeof(char*)*largo).

Resources