C Passing Pointer to Pointer to a Function and Using malloc - c

I'm trying to get std input to scan in two 2d parallel arrays (arrAtk, arrDef) of x rows (x<100), and y columns (y<1,000,000). But y is a variable length in each row.
The first line of input is x for the number of rows in each array.
the second line is y for the number of columns in the first row.
Following that is y integers to be read into the arrAtk array.
Then another y integers to be read into the arrDef array.
Directly following is an int y for the number of columns in the next two rows.
And so on.
The parallel arrays will hold integers that will be sorted later, and each parallel element will be compared to see which of the rows had higher numbers.
Problem: So I'm trying to scan the input with a function call and dynamically allocate the correct amount of memory and scan the input for each row of the 2d arrays.
This seems to work okay but then when I try to print the array values in main it crashes. The printf statements work in the scanIn function so I must not be passing values correctly. How can I get it to where I can use the dynamically created arrays outside of the function?
Thanks in advance
Example of std input:
2 //<- x num of rows
2 //<- y num of cols
3
6
5
2
3 //<- y num of cols
2
3
12
9
3
4
CODE:
#include <stdio.h>
#include <stdlib.h>
int scanIn(int**,int**,int*);
int main(){
int cases, *armies, **arrAtk, **arrDef;
cases = scanIn(arrAtk,arrDef,armies);
printf("%d\n",arrAtk[1][2]); // Should be 12 with above input
printf("%d",arrDef[0][1]); // Should be 2
return 0;
}
int scanIn(int **arrAtk, int **arrDef, int *armies){
int i, j, cases;
scanf("%d",&cases);
arrAtk = (int**)malloc(sizeof(int*)*cases);
arrDef = (int**)malloc(sizeof(int*)*cases);
armies = (int*)malloc(sizeof(int)*cases);
for(i=0;i<cases;i++){
scanf("%d",&armies[i]);
arrAtk[i] = malloc(sizeof(int)*armies[i]);
arrDef[i] = malloc(sizeof(int)*armies[i]);
for(j=0;j<armies[i];j++){
scanf("%d",&arrAtk[i][j]);
}
for(j=0;j<armies[i];j++){
scanf("%d",&arrDef[i][j]);
}
}
return (cases);
}

While there are better ways of doing this, it can be done with the approach you have taken. The first thing to note is you were passing each pointer to your function instead of the address of the pointer. When that occurs, your function receives a copy of the pointer, containing the proper address for the values (if initialized), but with a very different address of its own.
So when you allocate storage for each of your arrays in the function, the pointers in main are completely unchanged. They still point to nothing. In order to have the allocations reflected in main you must pass the address of the pointer to your function, and dereference accordingly in your function, so that the allocations are available in main.
The short version is you need to call your function with scanIn (&arrAtk, &arrDef, &armies) and your prototype must be (int***, int***, int**). (not particularly attractive)
One other issue is that style in C generally avoids the use of caMelCase variables (leave that for C++). See: (section 2.2) NASA C Style Guide (Goddard Spaceflight Center 1994)
Below is an example of the additional level of indirection required to make the allocation work as you intended. (note: you should also free the memory you allocate):
#include <stdio.h>
#include <stdlib.h>
int scan_in (int***, int***, int**);
int main (void) {
int cases, *armies, **arr_atk, **arr_def;
cases = scan_in (&arr_atk, &arr_def, &armies);
printf ("\n cases : %d\n", cases);
printf (" arr_atk[1][2] : %d\n", arr_atk[1][2]);
printf (" arr_def[0][1] : %d\n\n", arr_def[0][1]);
return 0;
}
int scan_in (int ***arr_atk, int ***arr_def, int **armies)
{
int i, j, cases;
scanf ("%d",&cases);
*arr_atk = malloc (sizeof **arr_atk * cases);
*arr_def = malloc (sizeof **arr_def * cases);
*armies = malloc (sizeof *armies * cases);
for (i = 0; i < cases; i++) {
scanf ("%d", &(*armies)[i]);
(*arr_atk)[i] = malloc (sizeof ***arr_atk * (*armies)[i]);
(*arr_def)[i] = malloc (sizeof ***arr_def * (*armies)[i]);
for (j = 0; j < (*armies)[i]; j++) {
scanf ("%d", &(*arr_atk)[i][j]);
}
for (j = 0; j < (*armies)[i]; j++) {
scanf ("%d", &(*arr_def)[i][j]);
}
}
return (cases);
}
Input
$ cat ../dat/2dscan.txt
2
2
3
6
5
2
3
2
3
12
9
3
4
Output
$ ./bin/2dscanin < ../dat/2dscan.txt
cases : 2
arr_atk[1][2] : 12
arr_def[0][1] : 2
note: since you are new to C, there are a few more areas where you can improve your code: (1) always initialize your variables that are not explicitly assigned a value in your code; (2) always validate the return values from the functions you call; and (3) always keep track of, and free the memory you allocate when it is no longer needed. Taking that into consideration, your main and scan_in code would look like:
int main (void) {
int i, cases = 0, *armies = NULL, **arr_atk = {NULL}, **arr_def = {NULL};
if ((cases = scan_in (&arr_atk, &arr_def, &armies)) < 1) {
fprintf (stderr, "error: invalid value for cases returned.\n");
return 1;
}
printf ("\n cases : %d\n", cases);
printf (" arr_atk[1][2] : %d\n", arr_atk[1][2]);
printf (" arr_def[0][1] : %d\n\n", arr_def[0][1]);
for (i = 0; i < cases; i++) { /* free allocated memory */
if (arr_atk[i]) free (arr_atk[i]);
if (arr_def[i]) free (arr_def[i]);
}
if (arr_atk) free (arr_atk);
if (arr_def) free (arr_def);
if (armies) free (armies);
return 0;
}
int scan_in (int ***arr_atk, int ***arr_def, int **armies)
{
int i, j, cases;
if (scanf ("%d",&cases) != 1) {
fprintf (stderr, "scan_in() error: input failure.\n");
return 0;
}
*arr_atk = malloc (sizeof **arr_atk * cases);
*arr_def = malloc (sizeof **arr_def * cases);
*armies = malloc (sizeof *armies * cases);
for (i = 0; i < cases; i++) {
if (scanf ("%d", &(*armies)[i]) != 1) {
fprintf (stderr, "scan_in() error: input failure.\n");
return 0;
}
(*arr_atk)[i] = malloc (sizeof ***arr_atk * (*armies)[i]);
(*arr_def)[i] = malloc (sizeof ***arr_def * (*armies)[i]);
for (j = 0; j < (*armies)[i]; j++) {
if (scanf ("%d", &(*arr_atk)[i][j]) != 1) {
fprintf (stderr, "scan_in() error: input failure.\n");
return 0;
}
}
for (j = 0; j < (*armies)[i]; j++) {
if (scanf ("%d", &(*arr_def)[i][j]) != 1) {
fprintf (stderr, "scan_in() error: input failure.\n");
return 0;
}
}
}
return (cases);
}

Related

free() function causes a breakpoint

{
char name_entry[ARRAY_SIZE];//bunu dinamik olarak atamıyorum her seferinde gireceğimiz ismin uzunluğunu sormak pratik olmayacaktır
int isimsayisi;
char** names;
printf("Kac Isim Gireceksiniz:");
scanf("%d", &isimsayisi);
names = (char**)malloc(sizeof(char) * (isimsayisi));
for (int k = 0; k < isimsayisi; k++) {
printf("\nismi giriniz :");
scanf("%s", name_entry);
names[k] = (char*)malloc(strlen(name_entry) + 1);
if (names[k] == NULL) {
printf("bellek yetersiz!..\n");
exit(EXIT_FAILURE);
}
strcpy(names[k], name_entry);
}
printf("\nGirilen Isimler : \n");
for (int k = 0; k < isimsayisi; k++) {
printf("%s \n", names[k]);
}
printf("\n");
for (int i = 0; i < isimsayisi; i++)
free(names[i]);
_getch();
}
In this code Im try to take names to a 2d string array then printf what have ı took from user then deallocate the memory but ı cant if I print free(names); after the for loop it gives a windows tab error. Its work like that to 2 names if I take more then 2 names its causes a breakpoint
Edit:isimsayisi means how much names the users wants to enter
This
names = (char**)malloc(sizeof(char) * (isimsayisi));
should be
names = malloc(sizeof(char *) * (isimsayisi));
you don't need to cast malloc() in C (different story for C++).
names is char **; therefore, when allocating memory, you need to use the sizeof(char *), which is definitely different than sizeof(char).
sizeof(char) is the size of a single character and is guaranteed to be 1, while sizeof(char *) is the size of an address and varies based on your machine (8 for a 64-bit CPU).

Read lines of text file into array, using double pointer and malloc

I want to read lines of a text file, and the content of it is as below.
first
second
third
I've already written some code, but the result was different from what I expected. I hope you can help me a little. (code below)
/*
content of test.txt
first
second
third
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
// double pointer for two string lines
// and the two string lines will be pointed by (char *) pointer
FILE *fp = fopen("test.txt", "r");
char **lst = malloc(3 * sizeof(char *)); // corrected 2 -> 3
// read lines until feof(fp) is not Null
// Only 2 lines will be read by this loop
int i = 0;
while (!feof(fp)) {
char line[10];
fgets(line, 10, fp);
*(lst + i) = line;
printf("%d : %s", i, *(lst + i));
i++;
}
/*
Result:
0 : first
1 : second
2 : third // Why was this line printed here?
There are 3 lines, not 2 lines!
*/
printf("\n\n");
int j;
for (j = 0; j < i; j++) {
printf("%d : %s\n", j, *(lst + j));
}
/*
result:
0 : third
1 : third
2 : third
The whole lines were not printed correctly!
*/
free(lst);
return 0;
}
Expected output:
0 : first
1 : second
2 : third
Many thanks.
First and foremost, you are allocating space for an array of two char*s and you have a single statically sized buffer for a string. But you’re attempting to read three strings. Where do you think the space for the strings is coming from? You’re not allocating it.
You need to make your various numbers match up: allocate an array of three strings, and then allocate three string buffers:
char **lst = malloc(3 * sizeof *lst);
for (int i = 0; i < 3; i++) {
lst[i] = malloc(10);
fgets(lst[i], 10, fp);
}
And don’t forget to free all allocated buffers subsequently:
for (int i = 0; i < 3; i++) {
free(lst[i]);
}
free(lst);
… of course this code isn’t terribly great either since it hard-codes the number of lines you can read, and the maximum line length. But it should get you started.

Dynamic array Vector in C

● int vectorInsert(Vector * array, int index, Data value);
I am doing
If this can be corrected according to the given statement.
I am calling it using
Vector *vect = initVector();
Data data_array[20];
for(i = 0 ; i < 20 ; i++){
data_array[i].value = (rand() % 20) + 1;
vectorInsert(vect, i, data_array[i]);
}
There are a couple of errors in your code, but the most important one is in your initVector function, you actually need to allocate memory for the vector.
You also need to do the following things:
in initVector return v instead of v->data or &v
in vectorInsert print array->data[index].value instead of array->data[index]
in vectorInsert return 1 on success, add error checking in your allocation and return 0 on memory error.
All of these except the original malloc were warnings returned by the compiler.
First, according to your specifications, max_size should be an unsigned integer, so I changed Vector to reflect this, using size_t. I also changed the related format specifiers from %d to %zu to match this new type.
Your initVector() function needed to allocate memory for a Vector, so that has been added. Furthermore, there was no need to allocate memory for the dynamic array of Data structs here, so v->data is set to NULL. This function should also return the pointer to the newly allocated memory, v, instead of a pointer to the .data field of this Vector, as you originally had.
In the vectorInsert() function, you neglected to check for memory allocation errors, so I added a check after the attempted allocation which returns 0 if there is an error. After inserting the new Data struct, your check to increment .current_size is wrong. First, you need to increment if array->current_size <= index. Next, you need to add one to the .current_size, not set .current_size to one larger than the index value. Also, when printing the inserted value here, you forgot to access the .value field. I think that this may have been due to the confusing name that you used for the Data struct that you passed into vectorInsert(). You call this struct value, so in the previous line we have array->data[index] = value, where you are assigning the struct value to array->data[index]. But in the call to printf() you want to show the value held by the struct value. Choosing better names is always a win! Finally, this function returns 1 on a successful insertion.
I added to your test code to display the contents of vect and vect->data, and also added a Data struct, test_insert, to test insertion into an arbitrary index.
Finally, you need to free memory allocations after all of this, so I added a couple of calls to free().
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
int value;
}Data;
/* Specs say that max_size should be an unsigned integer */
typedef struct{
size_t max_size; //initialize to 0
size_t current_size; //initialize to 0
Data *data; // array of integers we're storing
} Vector;
/* Modified function */
Vector * initVector(void){
Vector *v = malloc(sizeof(*v));
v->max_size=0;
v->current_size=0;
v->data = NULL;
return v;
}
int vectorInsert(Vector * array, size_t index, Data value)
{
if(index >= array->max_size)
{
array->max_size = index * 2 + 1;
printf("Inside Vect max_size is : %zu\n", array->max_size);
Data *new_array = malloc(sizeof(Data) * array->max_size);
/* Added check for allocation error */
if (new_array == NULL)
return 0;
if(array->data != NULL)
{
memcpy(new_array, array->data, sizeof(Data)*array->current_size);
free(array->data);
array->data = NULL;
}
array->data = new_array;
}
array->data[index] = value;
printf("Main : %d\n", array->data[index].value);
/* Modified current_size increment logic */
if(array->current_size <= index)
{
array->current_size += 1;
}
/* Successful insertion */
return 1;
}
int main(void)
{
size_t i;
Vector *vect = initVector();
Data data_array[20];
Data test_insert = { -5 }; // to test index insertion
for(i = 0 ; i < 20 ; i++){
data_array[i].value = (rand() % 20) + 1;
vectorInsert(vect, i, data_array[i]);
}
/* Display results */
printf("vect->max_size = %zu\n", vect->max_size);
printf("vect->current_size = %zu\n", vect->current_size);
printf("vect->data contains:\n");
for (i = 0; i < vect->current_size; i++)
printf("%d ", vect->data[i].value);
putchar('\n');
/* Insert test_insert at index 5 */
vectorInsert(vect, 5, test_insert);
/* Display results */
printf("vect->max_size = %zu\n", vect->max_size);
printf("vect->current_size = %zu\n", vect->current_size);
printf("vect->data contains:\n");
for (i = 0; i < vect->current_size; i++)
printf("%d ", vect->data[i].value);
putchar('\n');
/* Free memory allocations */
free(vect->data);
free(vect);
return 0;
}
And here is a sample of the results:
vect->max_size = 31
vect->current_size = 20
vect->data contains:
4 7 18 16 14 16 7 13 10 2 3 8 11 20 4 7 1 7 13 17
vect->max_size = 31
vect->current_size = 20
vect->data contains:
4 7 18 16 14 -5 7 13 10 2 3 8 11 20 4 7 1 7 13 17
Enable all warnings and debug info in your compiler (e.g. compile with gcc -Wall -g). Then it should warn you about
Vector * initVector(){
Vector *v; /// UNINITALIZED
v->max_size=0;
v->current_size=0;
v->data = malloc(sizeof(int)*v->max_size);
return v->data;
// return (&v);
}
So you have an undefined behavior, and that is awfully bad.
(Of course the compiler will give a lot of other warnings, and you should improve your code till you got no warnings at all. Then you should use the gdb debugger)
You might want to read about flexible array members.
Consider perhaps having at least:
Vector* createVector(int maxsize) {
if (maxsize<=0)
{ fprintf(stderr, "bad maxsize=%d\n", maxsize); exit(EXIT_FAILURE); };
Vector* v = malloc(sizeof(Vector));
if (!v) { perror("malloc Vector"); exit(EXIT_FAILURE); };
v->data = malloc(sizeof(Data)*maxsize);
if (!v->data) { perror("malloc data"); exit(EXIT_FAILURE); };
v->max_size = maxsize;
v->current_size = 0;
memset(v->data, 0, sizeof(Data)*maxsize);
return v;
}

Reallocation of Multi-dimensonal Pointer Array Causing Segmentation Fault

First, I'll explain why I'm doing this the way that I am. I'm taking a course in computer programming and my professor has given us an assignment where we have to make an array of records(each contains a first name, last name, & score), and then allow the user to manipulate the records using menu options. All of this MUST be done using only pointer arrays, and structures are not allowed. I know it is a headache. I know it probably one of the most difficult ways to accomplish this, but its what the professor wants.
With that out of the way, below is what I have for my main function so far. most of the long printf functions are just me printing debugging information. Please take note of the declaration of the char*** variable. It is meant to function as a 3D array where nameRecords[0] would be the first record, nameRecords[0][0] would be the first name of the first record, and nameRecords[0][1] is the last name of the first record. The third dimension is nameRecords[0][0][21], as the strings are only meant to be 20 characters long plus null character.
int main(void)
{
char ***nameRecords = NULL;
float *scores = NULL;
int size = 0; // total number of records
int usrInt = 0;
while(usrInt < 1)
{
printf("\nEnter the number of records to record(min 1): ");
scanf("%d", &usrInt);
inpurge();
if(usrInt < 1) printf("\nMust be integer greater than 1.\n");
}
nameRecords = (char***)calloc((size), sizeof(char**));
scores = (float*)calloc(size, sizeof(float));
int i;
for(i = 0; i < usrInt; i++)
{
addRecord(&nameRecords, &scores, &size);
printf("\nnameRecords#%p :: nameRecords[%d]#%p :: nameRecords[%d][0]=%s :: nameRecords[%d][1]=%s\n", nameRecords, size - 1, nameRecords[size - 1], size - 1, nameRecords[size - 1][0], size - 1, nameRecords[size - 1][1]);
}
printf("\nnameRecords[0]#%p\n", nameRecords[0]);
prntRecords(nameRecords, scores, size);
printf("\n\n\n");
return 0;
}
The trouble comes after I pass, for the SECOND TIME, &nameRecords into the addRecord function, defined below. To clarify, the segmentation fault is not received if the user chooses to enter only 1 entry at the beginning of the main function, and the program actually runs and terminates as expected.
void addRecord(char ****records, float **scores, int *size)
{
printf("\t(*records)[0]%p\n", (*records)[0]);
++*size; // increment total number of records by 1
int index = (*size) - 1;
char ***tempNames = (char***)realloc(*records, (*size) * sizeof(char**)); // reallocate larger space.
if(tempNames != *records)
*records = tempNames; // set original pointer to new value.
printf("\n\tsize - 1 = %d\n", index);
float *tempScores = (float*)realloc(*scores, (*size) * sizeof(float)); // reallocate larger space.
if(tempScores != *scores)
*scores = tempScores; // set original pointer to new value.
printf("\ttempNames[0]#%p\n", tempNames[0]);
tempNames[index] = (char**)calloc(tempNames[index], 2 * sizeof(char*));
enterRecord(tempNames[index], scores[index]);
printf("\n\ttempNames#%p :: tempNames[0]#%p :: tempNames[%d][0]=%s :: tempNames[%d][1]=%s\n", tempNames, tempNames[0], index, tempNames[index][0], index, tempNames[index][1]);
printf("\n\t*records#%p :: *records[0]#%p :: *records[%d][0]=%s :: *records[%d][1]=%s\n", *records, (*records)[0], index, (*records)[index][0], index, (*records)[index][1]);
return;
}
Below is an example output of the program. Without taking too long to explain whats happening, the tabbed lines are the lines of output from within the addRecord function. Specifically, the pointer to the first record, record[0], has been turned into a garbage value on the second pass through the addRecord function, just after the enterRecord function.
Enter the number of records to record(min 5): 2
(*records)[0](nil)
size - 1 = 0
tempNames[0]#(nil)
Enter first name: 1
Enter last name: 1
Enter score: 1
COMPLETE enterRecord
tempNames#0x6387010 :: tempNames[0]#0x6387050 :: tempNames[0][0]=1 :: tempNames[0][1]=1
*records#0x6387010 :: *records[0]#0x6387050 :: *records[0][0]=1 :: *records[0][1]=1
nameRecords#0x6387010 :: nameRecords[0]#0x6387050 :: nameRecords[0][0]=1 :: nameRecords[0][1]=1
(*records)[0]0x6387050
size - 1 = 1
tempNames[0]#0x6387050
Enter first name: 2
Enter last name: 2
Enter score: 2
COMPLETE enterRecord
tempNames#0x6387010 :: tempNames[0]#0x40000000 :: tempNames[1][0]=2 :: tempNames[1][1]=2
*records#0x6387010 :: *records[0]#0x40000000 :: *records[1][0]=2 :: *records[1][1]=2
nameRecords#0x6387010 :: nameRecords[1]#0x63870b0 :: nameRecords[1][0]=2 :: nameRecords[1][1]=2
nameRecords[0]#0x40000000
records#0x6387010 :: records[0]#0x40000000
Segmentation fault
All of the debug information points to the enterRecord function as being the culprit. So here it is, the evil enterRecord function...
void enterRecord(char **names, float *score)
{
names[0] = (char*)calloc(21, sizeof(char)); // allocate first name string
names[1] = (char*)calloc(21, sizeof(char)); // allocate last name string
printf("\nEnter first name: ");
fgets(names[0], 21, stdin);
if(strlen(names[0]) == 20) // IGNORE. just handles overflow from fgets.
inpurge();
remNewLine(names[0]); // removes '\n' character at end of string
printf("\nEnter last name: ");
fgets(names[1], 21, stdin);
if(strlen(names[1]) == 20) // IGNORE. just handles overflow from fgets.
inpurge();
remNewLine(names[1]); // removes '\n' character at end of string
printf("\nEnter score: ");
scanf("%f", score);
inpurge();
printf("\nCOMPLETE enterRecord\n");
return;
}
Only... no attempt at altering the affected pointer was made. The pointer value to the second element of the records array(records[1]) was passed into the function, and nothing I can see is altering the value of the pointer of the first element of the records array(records[0]), though the value of records[0] is what's causing the segfault.
I am very sorry for the length and all obfuscatory code. Again, this seems like a terrible approach to writing this program, but its what the situation calls for. I just feel bad for the poor teacher's aide who has to grade 30+ of these assignments.
Any help is welcomed.
this problem seems to be better implemented as
#define MAX_FIRST_NAME_LEN (21)
#define MAX_LAST_NAME_LEN (21)
#define MAX_SCORES (10)
// in file global memory...
static char **ppFirstNames = NULL;
static char **ppLastName = NULL;
static int **ppScores = NULL;
static int numOfEntries = 0;
// in the record input function, which needs NO parameters
scanf ( "%d", &numOfEntries );
if scanf fails, exit
ppFirstNames = malloc (numOfEntries*sizeof char*);
if malloc fails, exit
memset (ppFirstName, '\0', numOfEntries*sizeof char* );
ppLastName = malloc (numOfEntries*sizeof char*);
if malloc fails, free all, exit
memset (ppLastName, '\0', numOfEntries*sizeof char* );
ppScores = malloc (numOfEntries *sizeof int* );
if malloc fails, free all, exit
for(int i=0; i<numOfEntries; i++ )
ppFirstNames[i] = malloc( MAX_FIRST_NAME_LEN );
if malloc fails free all, exit
memset ( ppFirstNames[i], '\0', MAX_FIRST_NAME_LEN );
ppLastName[i] = malloc (MAX_LAST_NAME_LEN);
if malloc fails free all, exit
memset ( ppLastName[i], '\0', MAX_LAST_NAME_LEN );
ppScores[i] = malloc (MAX_SCORES *sizeof int);-1
if malloc fails, free all, exit
memset (ppScores[i], '\0', MAX_SCORES *sizeof int );
end for
for ( int i=0; i < numOfEntries; i++ )
now read each record
scanf( "%(MAX_FIRST_NAME_LEN-1)s", ppFirstNames[i] );
if scanf fails, free all, exit
scanf( "%(MAX_LAST_NAME_LEN-1)s", ppLastNames[i] );
if scanf fails, free all exit
for( int j=0; j< MAX_SCORES; j++ )
now read this students scores
int tempScore;
scanf( "%d", tempScore );
if scanf fails, free all, exit
if -1 == tempScore ) break;
ppScores[i][j] = tempScore;
end for
end for
The above is the pseudo code for inputting the records
and should be enough to get the input correct.
printing the info thereafter should be easy.
Example to use realloc for array multidimensional:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int size_initial = 10;
int **ptr;
int i, j;
ptr = (int**) malloc(sizeof (int*) * size_initial);
for (i = 0; i < size_initial; i++) {
ptr[i] = (int*) malloc(sizeof (int) * 10);
for (j = 0; j < 10; j++)
ptr[i][j] = i+j;
}
/* realloc +10 */
ptr = (int**) realloc(ptr, sizeof (int*) * (size_initial * 2));
for (i = size_initial; i < size_initial * 2; i++) {
ptr[i] = (int*) malloc(sizeof (int) * 10);
for (j = 0; j < 10; j++) {
ptr[i][j] = i+j;
}
}
/* print values */
for (i = 0; i < 20; i++) {
for (j = 0; j < 10; j++) {
printf("ptr[%d][%d] = %d\n", i, j, ptr[i][j]);
}
}
return 0;
}

Reallocation problems when assigning string to dynamic int array

Basically, I'm trying to convert a bunch of char inputs to ints and assign them to a dynamic int array. The string input and tokenization seem to work fine. The issue (from what I can tell) seems to be with the reallocation of the int array; after the array is reallocated twice, the pointer to the int array returns NULL.
What I tried to do was double the size of the int array every time the number of tokens meets or surpasses (size divided by sizeof(int)). The realloc statement works each time this condition is met.
I thought using a pointer to a pointer was the end-all solution to this. I bet it's some really obvious issue, but I'm at my wit's end here. If you request any further elaboration, I'll try my best. Understand that I've only taken C for a semester and have struggled most of the way.
Also, truth be told, this was part of a class assignment which has since passed. I'd prefer an explanation about what's wrong more than a full-on code, if that's alright.
I have a lot of printf statements, so apologies for any clutter.
EDIT: Replaced all instances of newArray within the input() function with *resize. However, I've never tried assigning values through pointers to pointers, so feel free to correct me with a syntactic example if you know how I messed up. Segmentation fault occurs here:
for (k = (numElem - count); k < numElem; k++)
{
printf("\nk = %i\n", k);
printf("j = %i\n", j);
printf("numElem = %i\n", numElem);
printf("results[j]: %s\n\n\n", results[j]);
/* Segmentation fault regardless of what is assigned
to *resize[k]. */
*resize[k] = atoi(results[j]); // PROBLEM HERE
j++;
}
The source code has been updated to reflect upon this. To make this ridiculously long post a little more subdued, let's state that I did this in main():
int *newArray = malloc(MAXTOKEN * sizeof(int));
input(&newArray);
free(newArray);
Moving on.
/* String input takes in char values,
tokenizes them, converts the results
to int, assigns them to newresizeay. */
int input(int **resize)
{
int i, j, k, count;
int numElem = 0;
int currentSize = MAXTOKEN;
char str[MAXSTRING];
char *results[MAXTOKEN];
/* This entire loop takes place at least once,
provided the first input isn't NULL. */
do
{
i = 0, j = 0, k = 0;
/* Char input process. Takes place until the user
presses ENTER. */
printf("Input integer values separated by spaces, or "
"press ENTER to exit.\n");
while ( ((str[i] = getchar() ) != '\n') && (i < MAXSTRING) )
i++;
printf("\n\n");
str[i] = '\0';
/* Tokenization of the chars that were input */
count = 0;
if (results[0] = strtok(str, " \t"))
count++;
while (results[count] = strtok(NULL, " \t") )
count++;
/* numElem = 1 if the first input prompt established
str[0] as NULL */
if ( (count < 1) && (numElem < 1) )
count = 1;
numElem += count;
printf("numElem: %i\ncurrentSize: %i\n", numElem, currentSize);
/* If the number of elements to assign meet or surpass
the amount of [memory / sizeof(int)], exponentially
increase the size of the int resizeay. */
if ( numElem >= currentSize )
{
*resize = realloc(*resize, (currentSize) * sizeof(int));
if (*resize == NULL)
printf("\n\nYep, it threw up.\n\n");
currentSize *= 2;
}
printf("\nSize should be: %i\n", currentSize * 4);
printf("Actual size: %d\n", _msize(*resize));
/* The tokenized chars are converted to integers and
assigned to the int resizeay. */
for (k = (numElem - count); k < numElem; k++)
{
printf("\nk = %i\n", k);
printf("j = %i\n", j);
printf("numElem = %i\n", numElem);
printf("results[j]: %s\n\n\n", results[j]);
*resize[k] = atoi(results[j]); // PROBLEM HERE
j++;
}
for (i = 0; i < numElem; i++)
printf("resize[%i]: %i\n", i, *resize[i]);
printf("\n\n\n");
} while (str[0] != NULL);
}
The input function receives both resize and arr. main sends the same pointer to both. This is a bug.
When resize is resized, arr stays the same and may point to an invalid address (when realloc returns a different address).
How to fix:
Remove arr function argument and only use resize.
When you call the realloc function,if the new memory block is smaller than previous ,it will maintain the original state pointing to the memory block which previous used.If the new memory block is larger than previous,the system will re allocate memory on the heap and the previous memory is released.
Among other problems:
char *results[MAXTOKEN];
should be
char *results[MAXTOKEN + 1];
because here the maximum value of count will be MAXTOKEN in this loop :
while (results[count] = strtok(NULL, " \t") )
count++;
and
char str[MAXSTRING];
is pretty scary, because as soon as the user enters more than MAXSTRIN (=11) characters without pressing Enter, you will get a buffer overflow.

Resources