Trouble Resizing a 2D Array in C - c

I have a project where I create a 2D char array that stores words, with the option to add more words, and then resize the array when necessary. I'm getting a variety of errors as I try to play with it and fix it so now I think I need some extra eyes on my code. I'm specifically looking for anything that obviously stands out as an incorrect or troublesome way of allocating memory or initializing an array.
The error I am getting specific to this code says "free(): invalid pointer" and leads to a SIGABRT. Below is my code.
Here is my resize function.
char ** resize_array(char **array)
{
int i;
char** tmp = malloc(2 * sizeof(*array));
int j;
for(j = 0; j < (2 * sizeof(*array)); j++)
tmp[j] = malloc(2 * sizeof(*array));
for(i = 0; i < (sizeof *words); i++)
{
strcpy(tmp[i], words[i]);
}
for(i = 0; words[i] != NULL; i++)
free(words[i]);
free(words);
return tmp;
}
Here is my resize function being implemented
int len;
len = (sizeof words);
if(upperbound > len) //upperbound keeps track of the word count
//and resizes the array
{
char **tmp = resize_array((char **) words);
int i;
for(i = 0; i <= upperbound; i++)
strcpy(words[i], tmp[i]);
}
And finally here is the "words" array as it is initially initialized.
char words[14][50];
I'm using VI and running everything on Ubuntu just fyi. Thanks in advance for everyones help!

Inside the resize_array function, you can't determine the previous size of the array using only a pointer to it.
The call to malloc
malloc(2 * sizeof(*array))
requests an allocation twice the size of a pointer to a char (only 16 bytes on a 64bit machine).
This is the first problem you need to fix.

Related

My program crashes when using realloc in C

#include <stdio.h>
#include <stdlib.h>
char **Names;
int size = 2; //Minimum size for 2D array
void main() {
int i;
Names = (char **)malloc(size * sizeof(char *)); // First initaliaion of 2D array in heap
for (i = 0; i < size; i++)
Names[i] = (char *)malloc(20 * sizeof(char));
printf("\nenter");
for (i = 0; i < size; i++)
scanf("%s", Names[i]);
while (1) {
size++;
Names = (char **)realloc(Names, size * sizeof(char *)); //Dynamic allocation of 2D aray
for (i = 0; i < size; i++)
Names[i] = (char *)realloc(Names[i], 20 * sizeof(char));
i = size - 1;
printf("\nenter");
scanf("%s", Names[i]);
for (i = 0; i < size; i++)
printf("\n%s", Names[i]);
}
}
It doesn't crash immediately it depends on the "size" I initialized.
It crashes after 5 allocations for me.
I tried adding free function but it did not seem to help.
After this memory reallocation
size ++;
Names= (char**)realloc(Names,size*sizeof(char *));
the last pointer pf the array of pointers has an indeterminate value because it was not initialized.
As a result the call of realloc for the last pointer in this loop
for (i=0; i<size; i++)
Names[i] = (char*)realloc(Names[i],20*sizeof(char));
invokes undefined behavior.
Before executing the loop you need to initialize the last pointer at least like
Names[size-1] = NULL;
In fact there is no sense to use the for loop because what you need is to allocate memory for the newly added pointer. The allocated memory pointed to by the early created pointers is not being changed in size.
So instead of
for (i=0; i<size; i++)
Names[i] = (char*)realloc(Names[i],20*sizeof(char));
you could just write
Names[size-1] = malloc( 20 * sizeof( char ) );
Pay attention to as you have an infinite loop then the memory reallocation sooner or later can fail.
Also according to the C Standard the function main without parameters shall be declared like
int main( void )

Creating a dynamic array of arrays using pointers

I'm trying to create a dynamic array of arrays. So, for example, let's look at Pascal's Triangle:
1
11
121
1331
14641
...
...
This is basically an array of length N, that has at each index an array of i+1.
How exactly do we set that up?
I've tried a little bit using pointers.
I set up an array of pointers like such:
int *arr[N];
Then I need a pointer i to point to an array of i+1, so I did:
int *i = 0;
for(int j = 0; j < N; j++){
int numArr[j+1];
arr[*i] = numArr;
*i++;
}
Am I going the right direction for this? Because I believe I'm supposed to allocate memory for this as I must use free() later. Would I use malloc() for each array initialization?
The code could be made extremely simple, if you know what you're doing:
int *arr = malloc(N * sizeof(int*));
int i;
for (i = 0; i < N; ++i) {
arr[i] = malloc(sizeof(int) * (i + 1));
}
Of course, you'll need corresponding calls to free() further down the line, like this:
for (i = 0; i < N; ++i) {
free(arr[i]);
}
free(arr);

Scanning to 2d array and then passing it to function - C

My program is getting segmentation fault if I allocate function as 1D array and then pass it to function. It is built for 2d array. Problem is, that I can't find out how to allocate 2d array and how to pass it correctly into function. Hope all is explained clearly. If you know what is wrong please try to lead me on correct way to fix it. Many thanks. Here is code:
int main()
{
int i, j, size;
scanf("%d", &size);
int *a;
//here i try to allocate it as 2d array
*a = (int *)malloc(size * sizeof(int));
for (i=0; i<size; i++)
{
a[i] = (int *)malloc(size * sizeof(int));
}
//here i scan value to 2d array
for (i = 0; i < size; i++)
for (j = 0; j < size; j++){
scanf("%d", &a[i][j]); }
//here i pass array and size of it into function
if (is_magic(a,size))
function header looks like:
int is_magic(int **a, int n)
This doesn't work:
*a = (int *)malloc(size * sizeof(int));
Because a has type int * so *a has type int, so it doesn't make sense to assign a pointer to that. You're also attempting to dereference a pointer which has not been initialized yet, invoking undefined behavior.
You need to define a as an int **:
int **a;
And assign to it directly on the first allocation, using sizeof(int *) for the element size:
a = malloc(size * sizeof(int *));
Note also that you shouldn't cast the return value of malloc.
Scanning 2D array ? For that you need to take a as of int** type not just int* type. For e.g
int **a = malloc(NUM_OF_ROW * sizeof(int*)); /* allocate memory dynamically for n rows */
And then allocate memory for each row for e.g
for (i=0; i<size; i++){
a[i] = malloc(NUM_OF_COLUMN * sizeof(int)); /* in each row how many column, allocate that much memory dynamically */
}

define pointer to pointer array

I want to use pointer to pointer to store a dynamic array data set but I don't know how to link them together. Does anyone know how to solve this problem?
How can I initialize the pointer to pointer array using dynamic array ? And how can I pick specific data set to do further program using pointer to pointer?
float *data;
float **dataIndex;
*dataIndex = (float**)malloc(number * sizeof(float*));
data = (float*) malloc(size * sizeof(float));
for(i = 0; i < size; i++){
scanf("%f", (data + i));
}
To dynamically allocate a 2D array, you will need to use a loop to initialize each pointer in the array.
float **arr;
size_t i, n;
if ((arr = malloc(n * sizeof(float *)) == NULL)
perror("malloc");
for (i = 0; i < n; ++i)
if ((arr[i] = malloc(sizeof (float))) == NULL)
perror("malloc");
Don't forget to free your memory.
while (--n >= 0)
free(arr[n]);
free(arr);
You need to be careful to free each subarray first, and then free the entire array.
That's not how allocate for pointer to pointers.
dataIndex = malloc(number * sizeof(float*));
for(i = 0; i < number; i++)
dataIndex[i] = malloc(size * sizeof(float));
Now if you want to populate data, you need to access it like a 2D array dataIndex[i][j].
for(i = 0; i < number; i++)
for(j = 0; j < size; j++)
scanf("%f", &dataIndex[i][j]);
Also remember to check errors and free memory.

Pass char** as an argument to a function in C

I know there are many topics of this kind but I've read several of them and still can't figure out what am I doing wrong.
I've successfully generated a char** array. My bubble sort function probably works as well. But when I passed the generated array to the function, only 1 row is copied.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
void sort(char** tab)
{
char* temp;
int i, j, size = sizeof(tab)/sizeof(tab[0]);
printf("%d\n", size);
for(i = 0; i < size; ++i)
{
for(j = i+1; j < size; ++j)
{
if(strcmp(tab[j-1], tab[j]) > 0)
strcpy(temp, tab[j-1]),
strcpy(tab[j-1], tab[j]),
strcpy(tab[j], temp);
}
}
for(i = 0; i < sizeof(tab)/sizeof(tab[0]); ++i)
puts(tab[i]);
}
int main()
{
srand(time(NULL));
int size = rand()%5+5, i, j, s;
char** tab = (char**)malloc(size * sizeof(char*));
for(i = 0; i < size; ++i)
{
s = rand()%9+1;
tab[i] = (char*)malloc(s+1);
for(j = 0; j < s; ++j)
tab[i][j] = 'a'+rand()%26;
tab[i][s] = 0;
}
for(i = 0; i < size; ++i)
puts(tab[i]);
puts("");
sort(tab);
return 0;
}
Here's how the code works.
And when I write size=5 before the loop in the function it returns segmentation fault.
Edit: Same with passing the size of the array as an argument:
http://ideone.com/3Wvncq
Final code
I've fixed all the problems and here's the final code.
I was misinterpreting segmentation fault as the result of assigning a fixed size instead of not allocating the temp variable.
Thank you for all the answers.
Don't calculate size inside function void sort(char** tab) . As in this function it will be calculated as -
int i, j, size = sizeof(tab)/sizeof(tab[0]); // equivalent to sizeof(char **)/sizeof(char*) in function giving wrong length as you desire.
It's length in main(size is generated using rand so no need to find it) and then pass it as argument to function sort.
Declare your function like this -
void sort(char** tab,size_t size)
And while calling from main pass length of tab to it -
sort(tab,size); // size will be number of elements in tab calculated in main
You get segmentation fault because of this -
if(strcmp(tab[j-1], tab[j]) > 0)
strcpy(temp, tab[j-1]),
strcpy(tab[j-1], tab[j]),
strcpy(tab[j], temp);
temp is uninitialized in sort and still you pass it to strcpy thus undefined behaviour . Initialize temp before passing to strcpy.Allocate memory to temp in function sort.
In your sort function you declare the temp variable:
char* temp;
Later you use it as destination (and source) for string copying:
strcpy(temp, tab[j-1]),
But nowhere in between do you make temp point anywhere, temp is uninitialized and that leads to undefined behavior and your crash.
Don't use a pointer, instead declare it as an array of the largest string size possible.

Resources