C String Allocation Wonkiness - c

Having trouble understanding and getting to work String operations in the following code.
Please help, me and my study colleagues are losing our minds over this. ty.
This is a simple method to fill a multi dimensional array with custom strings - which for some reason we cannot figure out for the life of us does simply not work - spits out random junk from the memory instead. Also allocation amounts don't seem to be quite right.
#include <stdio.h>
#include <malloc.h>
#include <string.h>
char*** createKeyPad(int rows, int cols, int num_chars) {
if(num_chars <= 0) return NULL;
char needed = 'a';
char** aptr = NULL;
char*** rptr = NULL;
aptr = (char**) malloc(rows * cols * sizeof(char*));
if(aptr == NULL) {
return NULL;
}
rptr = (char***) malloc(rows * sizeof(char**));
if(rptr == NULL) {
free(aptr);
return NULL;
}
for(int row = 0; row < rows; row++) {
rptr[row] = aptr + (row * cols);
}
for(int row = 0; row < rows; row++) {
for(int col = 0; col < cols; col++) {
char* string;
for(int i = 0; i < num_chars; i++) {
string[i] = needed;
}
string[num_chars] = '\0';
rptr[row][col] = string;
printf("%s", string);
}
}
printf("%s", "hallo");
return rptr;
}
int main() {
printf("Hello, World!\n");
char*** keypad = createKeyPad(5, 5, 3);
for(int row = 0; row < 5; row++) {
for(int col = 0; col < 5; col++) {
printf("%s", keypad[row][col]);
}
printf("\n");
}
}

You have plenty problems in this code.
string is a dangling pointer - ie it was not initialized and does not reference a valid char array
even if string was referencing a valid object you assign the same pointer to all (pseudo)array elements.
Do not use *** pointers.
use the correct type for sizes
Use positive checks and try to minimize function returns.
arrays are indexed from 0 in C and even if the string was referencing an array of num_chars elements, string[num_chars] = '\0'; is accessing an element outside the array bounds.
I would use array pointers and use only one allocation to allocate the space for the whole 3D array.
Use objects instead of types in sizeofs
int createKeyPad(size_t rows, size_t cols, size_t numChars, char (**pad)[cols][numChars])
{
int result = 0;
if(numChars > 1)
{
*pad = malloc(rows * sizeof(**pad));
if(*pad)
{
result = 1;
for(size_t row = 0; row < rows; row++)
{
for(size_t col = 0; col < cols; col++)
{
for(size_t i = 0; i < numChars - 1; i++)
{
(*pad)[row][col][i] = row * cols + col + '0';
}
(*pad)[row][col][numChars - 1] = 0;
}
}
}
}
return result;
}
int main(void)
{
printf("Hello, World!\n");
char (*keypad)[5][3];
if(createKeyPad(5, 5, 3, &keypad))
{
for(size_t row = 0; row < 5; row++)
{
for(size_t col = 0; col < 5; col++)
{
printf("%s ", keypad[row][col]);
}
printf("\n");
}
}
free(keypad);
}
https://godbolt.org/z/6zY4zbGW3

The main problem is that char* string; followed by string[i] = needed; is dereferencing an invalid pointer because string is not pointing to anything valid.
In the code's current style of allocating one block for each level and dividing the block up, the memory for all the strings could be allocated in one big block:
char* sptr = (char*) malloc(rows * cols * (num_chars + 1) * sizeof(char));
(Note: The (char*) typecast is not required. Also the * sizeof(char) is not required since sizeof(char) is 1 by definition, but I put it in there in case the code is changed to use something other than char at a later date.)
Then the string variable in the nested loop can be initialized as follows:
char* string = sptr + (row * cols + col) * (num_chars + 1);

Related

C how to put content of .txt file into 2D array

Working with C, I am trying to read from a .txt file, line by line, and then put every line into an array. Every line is 200 characters long maximum, and the array can store, lets say 50 lines. If the number of lines exceed 50, I want to dynamically allocate twice as much memory, and so on until it is enough. If I put the if{...} part outside of the while loop, it seems to work, but as soon as I use it inside of the loop it does not. I would appreciate any help.
FILE *fp=fopen(file,"r");
int idx=0;
int row=50;
int col=300;
char temp[row][col];
while (fgets(temp[idx],col,fp)){
if (idx == row) {
char **new = malloc(2 * row * sizeof(char *));
for (int j = 0; j < row; j++) {
new[j] = (char *) malloc(col * sizeof(char) + 1);
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < (col + 1); j++) {
new[i][j] = temp[i][j];
}
}
row = 2 * row;
**temp = **new;
free(new);
}
idx++;
}
fclose(fp);
You cannot change the dimensions of a local array (here temp[row][col]). Instead you need to keep a pointer to such an array. In the following code I use a temp array just to keep one line for fgets, and then copy it immediately into a dynamically allocated storage (arr is the 2d array of lines):
FILE *fp=fopen(file,"r");
int idx=0;
int row=50;
int col=300;
char temp[col];
char **arr = malloc(row*sizeof(char*));
while (fgets(temp,col,fp)){
if (idx == row) {
char **new = realloc(arr, 2 * row * sizeof(char *));
if(!new) abort();
arr = new;
row *= 2;
}
arr[idx++] = strdup(temp);
}
fclose(fp);

seg fault when I try to create a 2d array of structs

Why would I be getting a seg fault at the highlighted line. Am I accessing the 2d array wrong? tempMap is a 1d array with all the values for the 2d array, for example [0,1,0,0,0,0,1,0] and since I know the number of rows and columns I am trying to make it into a 2d array of Spaces (which is my struct). Any help is very much appreciated.
int opt;
char *filename = NULL;
Space **map;
char *tempMap;
if (i != 0){
int col = getCol(filename);
int row = getRow(filename, col);
printf("%d x %d\n", row, col);
map = create_map(row, col, filename);
tempMap = populate_map(map, filename);
int curIndx=0;
for (int l = 0; l < 100; ++l) {
printf("%c", tempMap[l]);
}
for (int j = 0; j < row; ++j) {
for (int k = 0; k < col; ++k) {
map[j][k] = makeNewSpace(tempMap[curIndx],row,col); //<-----------This Line
curIndx++;
}
}
}
Also here is the makeNewSpace()
Space makeNewSpace(char character, int row, int column){
Space space;
space.character = character;
space.isVisited = false;
space.row= row;
space.column = column;
return space;
}
And this is where I allocate space for the 2d array.
Space **create_map( int row, int col, char *fileName) {
Space *values = calloc(row * col, 2* sizeof(char) + (4 * sizeof(int)));
Space **map = malloc(row * sizeof(char *));
for (int i = 0; i < row; ++i) {
map[i] = values + i * col;
}
return map;
}
Lastly here is my struct
typedef struct Space{
char character;
bool isVisited;
int row;
int column;
}Space;
Not sure if this is what you're going for, a dynamically allocated 2d array of Space structs.
#include <stdio.h>
#include <stdlib.h>
// Space struct definition
typedef struct {
int data;
} Space;
int main() {
int i;
// Allocate memory for the rows
Space** space2d = malloc(sizeof(Space*) * 3);
// Allocate memory for the columns
for(i = 0; i < 3; ++i) {
space2d[i] = malloc(sizeof(Space) * 5);
}
// Example setting one of the struct's members inside the 2d array
space2d[0][0].data = 100;
printf("%d\n", space2d[0][0].data);
// Freeing the 2d array
for(i = 0; i < 3; ++i)
free(space2d[i]);
free(space2d);
}

Passing array of pointers as argument to function in C

I've written a piece of code but I'm not sure about how it works.
I want to create an array of pointers and pass it as argument to a function, like the following:
int main()
{
int *array[10] = {0};
for(int i = 0; i < 3; i++)
{
array[i] = (int *)malloc(3*sizeof(int *));
}
testFunction(array);
for(int i = 0; i < 3; i++)
{
free(array[i]);
}
return 0;
}
void testFunction(int *array[3])
{
//do something
return;
}
What I don't understand is the following. I declare array as an array of pointers, allocate memory to it by using malloc and then proceed to call testFunction. I want to pass the array by reference, and I understand that when I call the function by using testFunction(array), the array decays to a pointer to its first element (which will be a pointer also). But why in the parameters list I have to write (int *array[3]) with * and not just (int array[3])?
A parameter of type * can accept an argument of type [], but not anything in type.
If you write void testFunction(int arg[3]) it's fine, but you won't be able to access array[1] and array[2] and so on, only the first 3 elements of where array[0] points to. Also a comversion is required (call with testFunction((int*)array);.
As a good practice, it's necessary to make the function parametera consistent with what's passed as arguments. So int *array[10] can be passed to f(int **arg) or f(int *arg[]), but neither f(int *arg) nor f(int arg[]).
void testFunction(int **array, int int_arr_size, int size_of_array_of_pointers)
{
for(int j = 0; j < size_of_array_of_pointers; j++)
{
int *arrptr = array[j]; // this pointer only to understand the idea.
for(int i = 0; i < int_arr_size; i++)
{
arrptr[i] = i + 1;
}
}
}
and
int main()
{
int *array[10];
for(int i = 0; i < sizeof(array) / sizeof(int *); i++)
{
array[i] = malloc(3*sizeof(int));
}
testFunction(array, 3, sizeof(array) / sizeof(int *));
for(int i = 0; i < sizeof(array) / sizeof(int *); i++)
{
free(array[i]);
}
return 0;
}
Evering depends on what // do something means in your case.
Let's start from simple : perhaps, you need just array of integers
If your function change only values in array but does not change size, you can pass it as int *array or int array[3].
int *array[3] allows to work only with arrays of size 3, but if you can works with any arrays of int option int *array require additional argument int size:
void testFunction(int *array, int arr_size)
{
int i;
for(i = 0; i < arr_size; i++)
{
array[i] = i + 1;
}
return;
}
Next : if array of pointers are needed
Argument should be int *array[3] or better int **array (pointer to pointer).
Looking at the initialization loop (I changed sizeof(int *) to sizeof(int))
for(int i = 0; i < 3; i++)
{
array[i] = (int *)malloc(3*sizeof(int));
}
I suppose you need 2-dimension array, so you can pass int **array but with sizes of two dimensions or one size for case of square matrix (height equal to width):
void testFunction(int **array, int wSize, int hSize)
{
int row, col;
for(row = 0; row < hSize; row++)
{
for(col = 0; col < wSize; col++)
{
array[row][col] = row * col;
}
}
}
And finally : memory allocation for 2D-array
Consider the following variant of your main:
int main()
{
int **array;
// allocate memory for 3 pointers int*
array = (int *)malloc(3*sizeof(int *));
if(array == NULL)
return 1; // stop the program
// then init these 3 pointers with addreses for 3 int
for(int i = 0; i < 3; i++)
{
array[i] = (int *)malloc(3*sizeof(int));
if(array[i] == NULL) return 1;
}
testFunction(array, 3, 3);
// First, free memory allocated for int
for(int i = 0; i < 3; i++)
{
free(array[i]);
}
// then free memory allocated for pointers
free(array);
return 0;
}
Pay attention, that value returned by malloc should be checked before usage (NULL means memory was not allocated).
For the same reasons check can be added inside function:
void testFunction(int **array, int wSize, int hSize)
{
int row, col;
if(array == NULL) // check here
return;
for(row = 0; row < hSize; row++)
{
if(array[row] == NULL) // and here
return;
for(col = 0; col < wSize; col++)
{
array[row][col] = row * col;
}
}
}

Freeing malloc of unknown size

I'm trying to free the malloc that is generated with a not fixed number of arrays.
char ** get_moves(){
// some code
char **moves = malloc(sizeof(char *) * k); // 'k', could ranges between 1~9
if (!moves){
return NULL;
}
for(int i = 0; i < k; i++){
moves[i] = malloc(82);
if (!moves[i]) {
free (moves);
return NULL;
}
// more code
return moves;
}
int main(){
//some code
char **res = get_moves(some_input);
//more code
for (int i = 0; i < (sizeof(res)/sizeof(res[0)); i ++){
free(res[i]);
}
free(res);
}
In one of the inputs to get_move, res should have 2 arrays but the sizeof(res)/sizeof(res[0) gives me just 1.
How is the proper way to handle this?
The only way is to keep track of the element count of the array, if you don't want to pass it to every function when passing the array, you can combine both pieces of information in a struct, like here
#include <stdlib.h>
struct ArrayOfStrings
{
int count;
char **data;
};
struct ArrayOfStrings get_moves()
{
struct ArrayOfStrings result;
char **moves;
// some code
result.count = 0;
result.data = malloc(sizeof(char *) * k); // 'k', could ranges between 1~9
if (result.data == NULL)
return result;
result.count = k;
moves = result.data;
for (int i = 0; i < k; i++)
{
moves[i] = malloc(82);
if (moves[i] == NULL)
{
/* also free succesfully allocated ones */
for (int j = i - 1 ; j >= 0 ; --j)
free(moves[j]);
free(moves);
}
result.count = 0;
result.data = NULL;
return result;
}
// more code
return result;
}
int main(){
//some code
struct ArrayOfStrings res = get_moves(some_input);
//more code
for (int i = 0; i < res.count ; i ++)
free(res.data[i]);
free(res.data);
return 0; // you should return from main.
}
sizeof is not for the length of an object's content but for the size of a data type, it is computed at compile time.
So in your case
sizeof(res) / sizeof(res[0]) == sizeof(char **) / sizeof(char *) == 1
since sizeof(char **) == sizeof(char *) it's just the size of a pointer.
sizeof(res)
Returns the sizeof(double-pointer);
So if you intend to get the number of pointers stored then you might not get this by doing what you are doing.
You need to do something like
for(i=0;i<k;i++) /* As I see you are allocating k no of pointer Keep track of it*/
free(res[i]);
free(res);
res is in fact not an array of arrays of char type. Instead it is a pointer to pointer to char type. sizeof(res) will give you the size of char**. You need to keep track of the number of allocations.
Since the maximum number of arrays to allocate is small (9), you can simplify your code by allocating the maximum number. Fill the unused elements with NULL:
#define MAX_K 9
char **moves = malloc(sizeof(char *) * MAX_K);
for(int i = 0; i < k; i++){
...
}
for(int i = k; i < MAX_K; i++){
moves[i] = NULL;
}
To deallocate, just ignore the NULL pointers:
for (int i = 0; i < MAX_K; i ++){
if (res[i])
free(res[i]);
}
free(res);

How do we allocate a 2-D array using One malloc statement

I have been asked in an interview how do i allocate a 2-D array and below was my solution to it.
#include <stdlib.h>
int **array;
array = malloc(nrows * sizeof(int *));
for(i = 0; i < nrows; i++)
{
array[i] = malloc(ncolumns * sizeof(int));
if(array[i] == NULL)
{
fprintf(stderr, "out of memory\n");
exit or return
}
}
I thought I had done a good job but then he asked me to do it using one malloc() statement not two. I don't have any idea how to achieve it.
Can anyone suggest me some idea to do it in single malloc()?
Just compute the total amount of memory needed for both nrows row-pointers, and the actual data, add it all up, and do a single call:
int **array = malloc(nrows * sizeof *array + (nrows * (ncolumns * sizeof **array));
If you think this looks too complex, you can split it up and make it a bit self-documenting by naming the different terms of the size expression:
int **array; /* Declare this first so we can use it with sizeof. */
const size_t row_pointers_bytes = nrows * sizeof *array;
const size_t row_elements_bytes = ncolumns * sizeof **array;
array = malloc(row_pointers_bytes + nrows * row_elements_bytes);
You then need to go through and initialize the row pointers so that each row's pointer points at the first element for that particular row:
size_t i;
int * const data = array + nrows;
for(i = 0; i < nrows; i++)
array[i] = data + i * ncolumns;
Note that the resulting structure is subtly different from what you get if you do e.g. int array[nrows][ncolumns], because we have explicit row pointers, meaning that for an array allocated like this, there's no real requirement that all rows have the same number of columns.
It also means that an access like array[2][3] does something distinct from a similar-looking access into an actual 2d array. In this case, the innermost access happens first, and array[2] reads out a pointer from the 3rd element in array. That pointer is then treatet as the base of a (column) array, into which we index to get the fourth element.
In contrast, for something like
int array2[4][3];
which is a "packed" proper 2d array taking up just 12 integers' worth of space, an access like array[3][2] simply breaks down to adding an offset to the base address to get at the element.
int **array = malloc (nrows * sizeof(int *) + (nrows * (ncolumns * sizeof(int)));
This works because in C, arrays are just all the elements one after another as a bunch of bytes. There is no metadata or anything. malloc() does not know whether it is allocating for use as chars, ints or lines in an array.
Then, you have to initialize:
int *offs = &array[nrows]; /* same as int *offs = array + nrows; */
for (i = 0; i < nrows; i++, offs += ncolumns) {
array[i] = offs;
}
Here's another approach.
If you know the number of columns at compile time, you can do something like this:
#define COLS ... // integer value > 0
...
size_t rows;
int (*arr)[COLS];
... // get number of rows
arr = malloc(sizeof *arr * rows);
if (arr)
{
size_t i, j;
for (i = 0; i < rows; i++)
for (j = 0; j < COLS; j++)
arr[i][j] = ...;
}
If you're working in C99, you can use a pointer to a VLA:
size_t rows, cols;
... // get rows and cols
int (*arr)[cols] = malloc(sizeof *arr * rows);
if (arr)
{
size_t i, j;
for (i = 0; i < rows; i++)
for (j = 0; j < cols; j++)
arr[i][j] = ...;
}
How do we allocate a 2-D array using One malloc statement (?)
No answers, so far, allocate memory for a true 2D array.
int **array is a pointer to pointer to int. array is not a pointer to a 2D array.
int a[2][3] is an example of a true 2D array or array 2 of array 3 of int
To allocate memory for a true 2D array, with C99, use malloc() and save to a pointer to a variable-length array (VLA)
// Simply allocate and initialize in one line of code
int (*c)[nrows][ncolumns] = malloc(sizeof *c);
if (c == NULL) {
fprintf(stderr, "out of memory\n");
return;
}
// Use c
(*c)[1][2] = rand();
...
free(c);
Without VLA support, if the dimensions are constants, code can use
#define NROW 4
#define NCOL 5
int (*d)[NROW][NCOL] = malloc(sizeof *d);
You should be able to do this with (bit ugly with all the casting though):
int** array;
size_t pitch, ptrs, i;
char* base;
pitch = rows * sizeof(int);
ptrs = sizeof(int*) * rows;
array = (int**)malloc((columns * pitch) + ptrs);
base = (char*)array + ptrs;
for(i = 0; i < rows; i++)
{
array[i] = (int*)(base + (pitch * i));
}
I'm not a fan of this "array of pointers to array" to solve the multi dimension array paradigm. Always favored a single dimension array, at access the element with array[ row * cols + col]? No problems encapsulating everything in a class, and implementing a 'at' method.
If you insist on accessing the members of the array with this notation: Matrix[i][j], you can do a little C++ magic. #John solution tries to do it this way, but he requires the number of column to be known at compile time. With some C++ and overriding the operator[], you can get this completely:
class Row
{
private:
int* _p;
public:
Row( int* p ) { _p = p; }
int& operator[](int col) { return _p[col]; }
};
class Matrix
{
private:
int* _p;
int _cols;
public:
Matrix( int rows, int cols ) { _cols=cols; _p = (int*)malloc(rows*cols ); }
Row operator[](int row) { return _p + row*_cols; }
};
So now, you can use the Matrix object, for example to create a multiplication table:
Matrix mtrx(rows, cols);
for( i=0; i<rows; ++i ) {
for( j=0; j<rows; ++j ) {
mtrx[i][j] = i*j;
}
}
You should now that the optimizer is doing the right thing and there is no call function or any other kind of overhead. No constructor is called. As long as you don't move the Matrix between function, even the _cols variable isn't created. The statement mtrx[i][j] basically does mtrx[i*cols+j].
It can be done as follows:
#define NUM_ROWS 10
#define NUM_COLS 10
int main(int argc, char **argv)
{
char (*p)[NUM_COLS] = NULL;
p = malloc(NUM_ROWS * NUM_COLS);
memset(p, 81, NUM_ROWS * NUM_COLS);
p[2][3] = 'a';
for (int i = 0; i < NUM_ROWS; i++) {
for (int j = 0; j < NUM_COLS; j++) {
printf("%c\t", p[i][j]);
}
printf("\n");
}
} // end of main
You can allocate (row*column) * sizeof(int) bytes of memory using malloc.
Here is a code snippet to demonstrate.
int row = 3, col = 4;
int *arr = (int *)malloc(row * col * sizeof(int));
int i, j, count = 0;
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
*(arr + i*col + j) = ++count; //row major memory layout
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
printf("%d ", *(arr + i*col + j));

Resources