C: resize an array WITHOUT realloc() - c

I need to re-size a malloc'd C array. However, I'm not supposed to use realloc() (it's for an assignment). The below code keeps throwing double free or corruption (out) More specifically, this function seems to do nothing, since the program behaves the same whether I call it or not. I feel like I'm probably missing something basic. Can anyone help me out? Thanks a lot
void double_array_size(float *array, int *size) {
float *temp = NULL;
int i;
temp = (float *) malloc(*size * 2 * sizeof(float));
for (i = 0; i < *size; i++) {
temp[i] = array[i];
}
*size *= 2;
free(array);
array = temp;
}

Like BLUEPIXY said, pass a double pointer or if you don't want to, better this:
float *double_array_size(float *array, int *size) {
float *temp = NULL;
int i;
temp = (float *) malloc(*size * 2 * sizeof(float));
for (i = 0; i < *size; i++) {
temp[i] = array[i];
}
*size *= 2;
free(array);
return temp;
}
and to increase the performance of you code, do not use a for loop, use memcpy instead:
temp = (float *) malloc(*size * 2 * sizeof(float));
memcpy(temp, array, sizeof *array * *size);
You should always check the return value of malloc and friends. They might return NULL and depending on your code, you might have to react to this if you don't want your code to crash.
Another thing: if you are using C only, do not cast malloc and I suggest to use sizeof *var instead of sizeof(float) because you are hardcoding the type. Let's say that you have to change the type of the array. If you hardcore your types, you have to change the types everywhere, otherwise only in the declarations, much less work and fewer errors.
Sometimes you need more or less the same code for different types. Luckily in C++ you have templates, in C you have to use Macros, if you don't want to repeat basically the same code over and over, for example:
#define DOUBLE_ARRAY_SIZE(type) \
type *double_array_size_ ##type (type *array, size_t *size) {\
type *temp; \
temp = malloc(*size * 2 * sizeof *array);\
if(temp == NULL)\
return NULL;\
memcpy(temp, array, sizeof *array * *size);\
*size *= 2;\
free(array);\
return temp;\
}
And instead of writing the same code with different types over and over, you can do
DOUBLE_ARRAY_SIZE(int)
DOUBLE_ARRAY_SIZE(double)
DOUBLE_ARRAY_SIZE(record_t)
void foo()
{
int *ints = malloc(...);
record_t *recs = malloc(...);
...
new_ints = double_array_size_int(ints, ints_size);
new_recs = double_array_size_record_t(recs, recs_size);
....
}
I know that a lot of people will say do not use macros, they're evil and they are kind of true, but using them wisely may help you more thank you think. One of the reason you should try to hardcore the datatype as less as possible.
// edit my macro snippet, chux's suggestion with size_t

One problem with this code is that parameters are call-by-value, so you’re changing only the local copy of array and leaking memory. The value in the rest of the program is never updated. What you want to do is return the reallocated array.

Related

How to access elements of 2D array created with malloc, using pointers?

I have code like this:
#include <stdio.h>
#include <stdlib.h>
int main() {
int x=10;
int y=10;
int **data = (int**) malloc(x * sizeof(int));
if(!**data){
printf("Error");
return 1;
}
for(int i=0;i<x;i++){
*(data+i) = (int*) malloc(y * sizeof(int));
if(!*(data+i)){
printf("Error");
return 1;
}
}
for(int i=0;i<x;i++){
for(int j=0;j<y;j++){
data[i][j]=(i+1)*(j+1);
}
}
for(int i=0;i<x;i++){
for(int j=0;j<y;j++){
printf("%3i ",data[i][j]);
}
printf("\n");
}
return 0;
}
How can i access points of that array using pointers instead of data[i][j]?
I tried searching for answer but in every example I see people use data[x][y] option, i have to use pointers for accessing each element.
Also is error handling correct in that code?
if(!**data){
printf("Error");
return 1;
}
Here's a major problem, especially on 64-bit systems where sizeof(int) != sizeof(int *):
int **data = (int**) malloc(x * sizeof(int));
You allocate x times the size of int, not the size of pointer to int.
There is a good "trick" to always get the correct size, use sizeof *variable_youre_allocating_for. In your case it would be
int **data = malloc(x * sizeof *data);
This works because sizeof *data is done at compile-time, and the compiler knows that *data is of type int * and will use the correct size.
Also notice that I removed the cast, it's not needed in C.
Besides that, your use of the data is correct. Using data[i][j] is perfectly fine, if i and j are valid indexes, and data and data[i] have been properly initialized.
The important part is to remember that for any pointer or array a and index i, the expression a[i] is exactly equal to *(a + i). In fact, the compiler will translate a[i] to *(a + i). So for your pointer data, the expression *(data + i) is exactly equal to data[i]. And the latter is usually easier to read and understand, as well as less to write.

Generic bidimensional array

I want to create a bidimensional array like so:
void **mdeclaraMatrice(int nrLini,int nrColoane, int sizeOfElement)
{
int i;
void **m = malloc(nrLini * 4);
if(m==NULL)
return NULL;
for(i=0; i<nrLini; i++)
{
*(m + (i*4)) = malloc(nrColoane * sizeOfElement);
if(*(m + (i*4)) == NULL)
return NULL;
}
return m;
}
I whant to use it like this:
int **m = (int **)mdeclaraMatrice(n,m,sizeof(int));
but it doesn't work. What do I do wrong?
You should use m[i] instead of *(m+i*4) and let the compiler do the arithmetic.
In addition, you should deallocate the already-allocated memory in case of a failure.
Try this instead:
void **mdeclaraMatrice(int nrLini, int nrColoane, int sizeOfElement)
{
int i;
void **m = malloc(nrLini * sizeof(void*));
if (m == NULL)
return NULL;
for (i=0; i<nrLini; i++)
{
m[i] = malloc(nrColoane * sizeOfElement);
if (m[i] == NULL)
{
while (i-- > 0)
free(m[i]);
free(m);
return NULL;
}
}
return m;
}
[not an answer to the question, but to the indented usage of the proper answer as given by others]
To access the void pointer array as an array of int, doing this
int **m = (int **)mdeclaraMatrice(n,m,sizeof(int));
is not correct, as per the C-Standard only void* converts to any other pointer properly, void** doesn't necessarily. So it shall correctly be
void ** ppv = mdeclaraMatrice(n,m,sizeof(int));
int * pi = *ppv; /* Please note, there is NO casting necessary here! */
Then access the members like so:
pi[0] = 42
pi[1] = 43;
...
Which essently is the same as doing
*((int *) (pi + 0)) = 42;
*((int *) (pi + 1)) = 43;
which indeed does not make sense really as pi already is int*, so the fully correct approach (also taking into account the 2nd dimension) would be:
((int *)(ppv[0]))[0] = 42;
((int *)(ppv[0]))[1] = 43;
Which could be made usable by definging a macro:
#define GENERIC_ARRAY_ELEMENT(type, address, r, c) \
((type *)(address[r]))[c]
GENERIC_ARRAY_ELEMENT(int, ppv, 0, 0) = 42;
GENERIC_ARRAY_ELEMENT(int, ppv, 0, 1) = 43;
I will address the problem of allocation an array of void pointers and then interpreting them as an array of int pointers.
int **nope = (int **)mdeclaraMatrice(n,m,sizeof(int));
Even assuming the allocation was completely correct the assignment and later usage of nope is undefined behavior. void** and int** have incompatible types.
What you can do is the following. Assign the void pointers one by one to an array of int pointers.
void** arrp = mdeclaraMatrice(n,m,sizeof(int));
int* arr[n] ;
for( size_t i = 0 , i < n ; i++ )
arr[i] = arrp[i] ;
And then use the arr array, When you want to free the memory you free the original pointer:
free( arrp ) ;
The problem occurs in this line:
*(m + (i*4)) = malloc(nrColoane * sizeOfElement);
You have to know that when adding a number to an address, the address will be incremented by the number times the size of the object the address points to. So if your pointer points to an object that is of size 4 bytes, and you add 1 to it, then the address will automatically be incremented by 4, not by 1. So you should abandon *4.
Also, use the sizeof operator when allocating space, because addresses (and thus pointers) can have different sizes on different processor architectures.
Actually, you don't even need your generic 2D array function if you know the powerfull VLA features of C99. To allocate a true 2D array (no index array required), you just do this:
int (*twoDIntArray)[width] = malloc(height*sizeof(*twoDIntArray));
That's it. Accesses are just as simple:
twoDIntArray[line][column] = 42;
In this code, twoDIntArray is a pointer to an array of width integers. The malloc() call simply allocates enough space for height such line arrays. When you do the pointer arithmetic twoDIntArray[line], you add the size of line line arrays to the pointer, which produces the address of the corresponding line array. This line array is then indexed by the second array subscript [column].
Needless to say that freeing such an array is just as trivial:
free(twoDIntArray);

Segmentation fault (core dumped) [Conway's game of life]

I'm working on a C implementation for Conway's game of life, I have been asked to use the following header:
#ifndef game_of_life_h
#define game_of_life_h
#include <stdio.h>
#include <stdlib.h>
// a structure containing a square board for the game and its size
typedef struct gol{
int **board;
size_t size;
} gol;
// dynamically creates a struct gol of size 20 and returns a pointer to it
gol* create_default_gol();
// creates dynamically a struct gol of a specified size and returns a pointer to it.
gol* create_gol(size_t size);
// destroy gol structures
void destroy_gol(gol* g);
// the board of 'g' is set to 'b'. You do not need to check if 'b' has a proper size and values
void set_pattern(gol* g, int** b);
// using rules of the game of life, the function sets next pattern to the g->board
void next_pattern(gol* g);
/* returns sum of all the neighbours of the cell g->board[i][j]. The function is an auxiliary
function and should be used in the following function. */
int neighbour_sum(gol* g, int i, int j);
// prints the current pattern of the g-board on the screen
void print(gol* g);
#endif
I have added the comments to help out with an explanation of what each bit is.
gol.board is a 2-level integer array, containing x and y coordinates, ie board[x][y], each coordinate can either be a 1 (alive) or 0 (dead).
This was all a bit of background information, I'm trying to write my first function create_default_gol() that will return a pointer to a gol instance, with a 20x20 board.
I then attempt to go through each coordinate through the 20x20 board and set it to 0, I am getting a Segmentation fault (core dumped) when running this program.
The below code is my c file containing the core code, and the main() function:
#include "game_of_life.h"
int main()
{
// Create a 20x20 game
gol* g_temp = create_default_gol();
int x,y;
for (x = 0; x < 20; x++)
{
for (y = 0; y < 20; y++)
{
g_temp->board[x][y] = 0;
}
}
free(g_temp);
}
// return a pointer to a 20x20 game of life
gol* create_default_gol()
{
gol* g_rtn = malloc(sizeof(*g_rtn) + (sizeof(int) * 20 * 20));
return g_rtn;
}
This is the first feature I'd like to implement, being able to generate a 20x20 board with 0's (dead) state for every coordinate.
Please feel free to criticise my code, I'm looking to determine why I'm getting the segmentation fault, and if I'm allocating memory properly in the create_default_gol() function.
Thanks!
The type int **board; means that board must contain an array of pointers, each of which points to the start of each row. Your existing allocation omits this, and just allocates *g_rtn plus the ints in the board.
The canonical way to allocate your board, supposing that you must stick to the type int **board;, is:
gol* g_rtn = malloc(sizeof *g_rtn);
g_rtn->size = size;
g_rtn->board = malloc(size * sizeof *g_rtn->board);
for (int i = 0; i < size; ++i)
g_rtn->board[i] = malloc(size * sizeof **g_rtn->board);
This code involves a lot of small malloc chunks. You could condense the board rows and columns into a single allocation, but then you also need to set up pointers to the start of each row, because board must be an array of pointers to int.
Another issue with this approach is alignment. It's guaranteed that a malloc result is aligned for any type; however it is possible that int has stricter alignment requirements than int *. My following code assumes that it doesn't; if you want to be portable then you could add in some compile-time checks (or run it and see if it aborts!).
The amount of memory required is the sum of the last two mallocs:
g_rtn->board = malloc( size * size * sizeof **g_rtn->board
+ size * sizeof *g_rtn->board );
Then the first row will start after the end of the row-pointers (a cast is necessary because we are converting int ** to int *, and using void * means we don't have to repeat the word int):
g_rtn->board[0] = (void *) (g_rtn->board + size);
And the other rows each have size ints in them:
for (int i = 1; i < size; ++i)
g_rtn->board[i] = g_rtn->board[i-1] + size;
Note that this is a whole lot more complicated than just using a 1-D array and doing arithmetic for the offsets, but it was stipulated that you must have two levels of indirection to access the board.
Also this is more complicated than the "canonical" version. In this version we are trading code complexity for the benefit of having a reduced number of mallocs. If your program typically only allocates one board, or a small number of boards, then perhaps this trade-off is not worth it and the canonical version would give you fewer headaches.
Finally - it would be possible to allocate both *g_rtn and the board in the single malloc, as you attempted to do in your question. However my advice (based on experience) is that it is simpler to keep the board separate. It makes your code clearer, and your object easier to use and make changes to, if the board is a separate allocation to the game object.
create_default_gol() misses to initialise board, so applying the [] operator to it (in main() ) the program accesses "invaid" memory and with ethis provokes undefined behaviour.
Although enough memory is allocated, the code still needs to make board point to the memory by doing
gol->board = ((char*) gol) + sizeof(*gol);
Update
As pointed out by Matt McNabb's comment board points to an array of pointers to int, so initialisation is more complicate:
gol * g_rtn = malloc(sizeof(*g_rtn) + 20 * sizeof(*gol->board));
g_rtn->board = ((char*) gol) + sizeof(*gol);
for (size_t i = 0; i<20; ++i)
{
g_rtn->board[i] = malloc(20 * sizeof(*g_rtn->board[i])
}
Also the code misses to set gol's member size. From what you tell us it is not clear whether it shall hold the nuber of bytes, rows/columns or fields.
Also^2 coding "magic numbers" like 20 is bad habit.
Also^3 create_default_gol does not specify any parameters, which explictily allows any numberm and not none as you might perhaps have expected.
All in all I'd code create_default_gol() like this:
gol * create_default_gol(const size_t rows, const size_t columns)
{
size_t size_rows = rows * sizeof(*g_rtn->board));
size_t size_column = columns * sizeof(**g_rtn->board));
gol * g_rtn = malloc(sizeof(*g_rtn) + size_rows);
g_rtn->board = ((char*) gol) + sizeof(*gol);
if (NULL ! = g_rtn)
{
for (size_t i = 0; i<columns; ++i)
{
g_rtn->board[i] = malloc(size_columns); /* TODO: Add error checking here. */
}
g_rtn->size = size_rows * size_columns; /* Or what ever this attribute is meant for. */
}
return g_rtn;
}
gol* create_default_gol()
{
int **a,i;
a = (int**)malloc(20 * sizeof(int *));
for (i = 0; i < 20; i++)
a[i] = (int*)malloc(20 * sizeof(int));
gol* g_rtn = (gol*)malloc(sizeof(*g_rtn));
g_rtn->board = a;
return g_rtn;
}
int main()
{
// Create a 20x20 game
gol* g_temp = create_default_gol();
int x,y;
for (x = 0; x < 20; x++)
{
for (y = 0; y < 20; y++)
{
g_temp->board[x][y] = 10;
}
}
for(x=0;x<20;x++)
free(g_temp->board[x]);
free(g_temp->board);
free(g_temp);
}
main (void)
{
gol* gameOfLife;
gameOfLife = create_default_gol();
free(gameOfLife);
}
gol* create_default_gol()
{
int size = 20;
gol* g_rtn = malloc(sizeof *g_rtn);
g_rtn = malloc(sizeof g_rtn);
g_rtn->size = size;
g_rtn->board = malloc(size * sizeof *g_rtn->board);
int i, b;
for (i = 0; i < size; ++i){
g_rtn->board[i] = malloc(sizeof (int) * size);
for(b=0;b<size;b++){
g_rtn->board[i][b] = 0;
}
}
return g_rtn;
}
Alternatively, since you also need to add a create_gol(size_t new_size) of custom size, you could also write it as the following.
main (void)
{
gol* gameOfLife;
gameOfLife = create_default_gol();
free(gameOfLife);
}
gol* create_default_gol()
{
size_t size = 20;
return create_gol(size);
}
gol* create_gol(size_t new_size)
{
gol* g_rtn = malloc(sizeof *g_rtn);
g_rtn = malloc(sizeof g_rtn);
g_rtn->size = new_size;
g_rtn->board = malloc(size * sizeof *g_rtn->board);
int i, b;
for (i = 0; i < size; ++i){
g_rtn->board[i] = malloc(sizeof (int) * size);
for(b=0;b<size;b++){
g_rtn->board[i][b] = 0;
}
}
return g_rtn;
}
Doing this just minimizes the amount of code needed.

Write a function to malloc double pointer

I need to write a function that creates a double pointer using malloc.
This is how I declared my double pointer as I normally would:
double **G; //Create double pointer to hold 2d matrix
*G = malloc(numNodes * sizeof(double*));
for(i = 0; i < numNodes; i++)
{
G[i] = malloc(numNodes*sizeof(double));
for (j = 0; j < numNodes; j++)
{
G[i][j] = 0;
}
}
Now I tried replacing it with:
double **G;
mallocDoubleArr(G, numNodes);
With the function being:
void mallocDoubleArr(double **arr, int size)
{
int i, j;
*arr = malloc(size * sizeof(double*));
for(i = 0; i < size; i++)
{
arr[i]= malloc(size*sizeof(double));
for (j = 0; j < size; j++)
{
arr[i][j] = 0;
}
}
}
Why doesn't this work?
You need one more "indirection", in other words pass G by reference like a pointer to a pointer to a pointer to float:
void mallocDoubleArr(double ***arr, int size);
And then call it as
mallocDoubleArr(&G, numNodes);
Modify mallocDoubleArr accordingly, like for example
(*arr)[i] = malloc(size*sizeof(double));
For starters, you need to change the line
*G = malloc(numNodes * sizeof(double*));
to
G = malloc(numNodes * sizeof(double*));
(you can't dereference a pointer safely until you've assigned something to it.)
Secondly, your function modifies the pointer passed in, so you need a pointer to it. Your signature should instead by
void mallocDoubleArr(double ***arr, int size)
and you will need to add the relevant indirections in your code to access the pointer that the pointer is pointing to.
A lot of confusion for beginners working with pointers comes from, in my opinion, thinking that they are something different than regular old variables. Pointers, like ints, floats, etc. are just variables that live on the stack: they have addresses, and they are passed to functions the same way. If you want to change a variable (int, float, pointer, etc) in a function, you need to pass a pointer to it. There is no difference in this regard.
C is call-by-value. In
double **G;
mallocDoubleArr(G, numNodes);
you are passing an uninitialized variable to mallocDoubleArr. It may be zero, it may be something else, but it almost certainly isn't something that mallocDoubleArr can assign to.
We can change the code, and the function's definition, to pass in G's address, but then you're dealing with yet another level of pointer. That might make it harder to understand the code. If that really isn't a requirement, I'd propose instead to have mallocDoubleArr return a double**.
double **G;
G = mallocDoubleArr(numNodes);
double **mallocDoubleArr(int size)
{
int i, j;
double **arr;
arr = (double **) malloc(size * sizeof(double *));
/* continue with old code */
return arr;
}
[edit: bstamour's post was made while I was writing mine. Sorry for any overlap.]
I use for matrix operations code like following for allocating and freeing.
int **inputMatrix, i, j;
Grid myGrid = *grid;
inputMatrix = (int *) calloc (myGrid.num_nodes, sizeof(int*));
for(i=0; i < myGrid.num_nodes; i++){
inputMatrix[i] = calloc(myGrid.num_nodes, sizeof(int));
for(j=0;j<myGrid.num_nodes;j++){
inputMatrix[i][j] = 0;
}
};
for(i=0; i < myGrid.num_nodes; i++){
free(inputMatrix[i]);
}
free (inputMatrix);

How to assign anything to array in this C function?

I have this C function:
fill_array(&data, &size);
void fill_array(int **data, int *size){
printf("Size is:");
scanf("%d", size);
*data = malloc(*size * sizeof(int *));
int i = 0;
for (i = 0; i < size; i++){
(*data)[i] = rand() % 11;
}
}
I want to assign data[i] for example, to random number. How to do such a thing? I have tried many variations, but all of the time my program crashes.
Thanks.
*data = malloc(*size * sizeof(**data));
(*data)[5] = 15;
Refer to cdecl web site.
Do not cast malloc
Edit according to the question edit
the for loop contains typo
for (i = 0; i < size; i++)
it should be
for (i = 0; i < *size; i++)
you can use (*data)[5] = 15; instead of this *data[5] = 15; Because precedence of [] greater than precedence of *..
As others said, you need to put parentheses to get the operator precedence right. If you want to use the "array" a lot, it might make sense to create a temporary variable that is easy to use:
int *p;
...
*data = malloc(*size * sizeof **data);
p = *data;
And then you could use p[5] etc.
Good program design dictates that we should keep memory allocation and the actual algorithm separated. To have a function that takes user input and allocates memory and performs some algorithm is probably not the optimal program design.
So the proper solution is not to patch that function to make it work, but instead to make some new ones:
int get_size_from_user (void)
{
int size;
printf("Size is:");
scanf("%d", &size);
return size;
}
bool alloc_array (int** array, int size)
{
*array = malloc(size * sizeof(int));
return *array != NULL;
}
void fill_array (int* array, int size)
{
// ...whatever you want to do here
data[5] = 15;
}
And look at that, the need for obscure syntax disappeared as soon as we improved the program design! Coincidence?

Resources