Why does this C programm crash? [duplicate] - c

This question already has answers here:
How much memory would be freed if pointer is changed in C?
(3 answers)
Closed 5 years ago.
I have written the following code, however I get a crash (without warnings or errors) and do not know the cause:
const int N = 1000;
int main(){
int *pI = calloc(N,sizeof(int));
for (int i=0;i<N;i++) {
*(pI++) = (i+1);
}
free(pI);
return EXIT_SUCCESS;
}
I am thankful for any advice!

You are not releasing the original pointer received from calloc():
free(pI);
You have been modifying the value contained in this pointer:
*(pI++) = (i+1);
Do instead:
int *p = calloc(N,sizeof(int));
int *pI = p;
// ...
free(p);
That is, save the value returned from calloc() and then pass it to free() when you don't need the allocated memory anymore.

Related

Why can I use more array values ​than allocated when using realloc in C [duplicate]

This question already has answers here:
How many members calloc allocates in C [duplicate]
(4 answers)
Malloc and array index confusion in C
(4 answers)
No out of bounds error
(7 answers)
Closed 4 months ago.
Test Case: I want to allocate memory using realloc() on an int array. I allocate memory for 2 values, but if I write the third value and so on to the array, they are also written and displayed. Why am I not getting a SegFault error?
P.s Exactly the same problem when using malloc()
#include <stdio.h>
#include <stdlib.h>
typedef struct Test
{
int *nums;
} Test;
int main()
{
Test test;
test.nums = NULL;
test.nums = realloc(test.nums, 2 * sizeof(int));
test.nums[0] = 1;
test.nums[1] = 2;
test.nums[2] = 3;
test.nums[3] = 4;
test.nums[4] = 5;
printf("%d %d %d %d %d\n", test.nums[0], test.nums[1], test.nums[2], test.nums[3], test.nums[4]);
free(test.nums);
return 0;
}

Using a multidimensional array within a structure [duplicate]

This question already has answers here:
Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer
(5 answers)
Closed 5 years ago.
I have written the following code:
#include <stdio.h>
#include <stdlib.h>
typedef struct _NeuralNetwork{
int input_rows;
int input_columns;
double **inputs;
}NeuralNetwork;
void main(){
// structure variable
NeuralNetwork *nn;
int count;
int i,j;
nn->input_rows = 2;
nn->input_columns = 3;
// create the array of double pointers using # of rows
nn->inputs = (double **)malloc(nn->input_rows * sizeof(double *));
// each pointer gets an array of double values
for (i=0; i<nn->input_rows; i++){
nn->inputs[i] = (double *)malloc(nn->input_columns * sizeof(double));
}
// assign values
count = 0;
for (i = 0; i < nn->input_rows ; i++)
for (j = 0; j < nn->input_columns; j++)
nn->inputs[i][j] = ++count;
// print those values
for (i = 0; i<nn->input_rows; i++)
for (j = 0; j < nn->input_columns; j++)
printf("%f ", nn->inputs[i][j]);
/* Code for further processing and free the
dynamically allocated memory*/
return;
}
When I compile this everything is okay. But after running it, I get a segmentation fault error:
Segmentation fault (core dumped)
I am not sure, where the mistake is. Can somebody help?
Note: When I use nn as structure variable instead of a structure, then everything is fine. But I want to use it as structure pointer and access the structure members via "->" and not via "." since I plan to pass nn as pointer to another function later.
Thank you in advance :)
The variable nn is a pointer, but that pointer is never initialized. You subsequently read and dereference that pointer using an operation such as nn->input_rows = 2;. This invokes undefined behavior.
In this particular case, nn likely contains some garbage value. By dereferencing that pointer value, you are attempting to read from memory you probably aren't allowed to. This is what causes the crash.
By defining nn as an instance of a struct instead of a pointer, as you said you tried, you avoid this issue. You can still however pass a pointer to other functions by taking the address of this variable and passing that to the function, i.e.:
NeuralNetwork nn;
...
myfunction(&nn)
First, do not use void main(), it's non-standard and would eventually cause problems. The right way is int main() or int main(int argc, char** argv). Remember to return a proper value at the end of the main function, possibly 0. Consult the reference here: main function
Second, if you use NeuralNetwork *nn; you must allocate some space for it in memory. It's a pointer to some memory address, if you don't allocate it who knows where it points. That's why you're getting the segfault. You must allocate memory for it in the following way:
NeuralNetwork *nn = malloc(sizeof(NeuralNetwork));
Then it should work properly.

Passing a pointer to an array and allocating memory [duplicate]

This question already has answers here:
Is it possible to allocate array inside function and return it using reference?
(3 answers)
How can I allocate memory for array inside a function
(5 answers)
How to use pointers to allocate an array inside another function
(2 answers)
Allocate memory 2d array in function C
(8 answers)
Closed 5 years ago.
I'm trying to pass a pointer from main to a function I wrote, which suppose to allocate memory with the size integer and receive input from the user.
Now I know I'm doing something wrong because the pointer doesn't change back in the main function. could someone tell me what exactly I did wrong?
int rows, *newCol=NULL // the pointer inside main();//rows is the size of the array.
the function:
void buildArr(int *newCol, int rows);
void buildArr(int *newCol, int rows)
{
int i;
newCol = (int*)malloc(sizeof(int)*rows);
for (i = 0; i<rows; i++)
{
printf("enter the value of the newCol:\n");
printf("value #%d\n", i + 1);
scanf("%d", &newCol[i]);
}
}
The pointer shouldn't change in the callee. C is pass by value.
Pass the address of the pointer variable
Call it like
buildArr(&newCol,rows);
...
...
void buildArr(int **newCol, int rows)
{
int i;
*newCol = malloc(sizeof(int)*rows);
...
scanf("%d", &(*newCol)[i]);
}
// nothing is returned.
}
Or return the address of the allocated chunk
newCol = buildArr(newCol, rows);
...
...
int* buildArr(int *newCol, int rows)
{
int i;
newCol = malloc(sizeof(int)*rows);
...
scanf("%d", &newCol[i]);
...
return newCol;
}

Returning array address from function [duplicate]

This question already has answers here:
Returning Arrays/Pointers from a function
(7 answers)
Closed 8 years ago.
I was trying to pass the array address from the function to the main function that's happening perfectly. But when I dereference the address in main(), I am getting junk values. I am guessing that the variables in the array_address memory lives only within the scope of the function. If this is the case, how do you return an array generated within a function to another function?
Here's my code:
int* letssee(int something)
{
int* array_address;
int a[10], i=0;
array_address = &a[0];
for (i; i<something;i++)
{
*(array_address+i) = i;
printf("\n%p, %d",(array_address+i), *(array_address+i));
}
return array_address;
}
int main()
{
int i= 5,j;
int* catch_address;
catch_address = letssee(i);
printf("\n");
for (j= 0; j<i; j++)
{
printf("%p, %d\n", (catch_address+j),*(catch_address+j));
}
return 0;
}
you can't return an array defined in a function as it is allocated on the stack and will disappear after the function has finished. Instead you allocate memory
int *array_address = malloc(sizeof(int) * 10);
however, you have to manage the memory, meaning you have to "free" it when you are finished with it, otherwise you will leak memory
The other approach is to pass the memory preallocated into a function (whether it be via malloc or the stack or global)
int* letsee(int something, int* array_address, int count);
if you simply make the array static, you are effectively making a global variable, multiple calls to the function will return the SAME address and may cause strange behaviour if you are expecting new arrays for each call.

malloc 2d arrays in C [duplicate]

This question already has answers here:
Using malloc for allocation of multi-dimensional arrays with different row lengths
(8 answers)
Closed 9 years ago.
I have a structure to store information in a 2D array:
struct slopes {
int size;
int ** slope_array;
};
I malloc the required memory for the structure(the array has dimensions of s*s):
struct slopes * slope=malloc(sizeof(struct slopes));
slope->size=s;
slope->slope_array=malloc(sizeof(int *)*s);
int i;
for(i=0;i<s;i++) {
slope->slope_array=malloc(sizeof(int)*s);
}
But lines such as these seem to throw segmentation errors:
slope->slope_array[0][0]=3;
Can someone see what I'm doing wrong?
In your for loop, you need to initialize slope->slope_array[i], not slope->slope_array:
for (i = 0; i < s; i++) {
slope->slope_array[i] = malloc(sizeof(int)*s);
}
Note: if you had cast the return call from malloc to an int *, the compiler would have warned you about this error...
There is a simple bug in your code, in the for loop do not assign the pointer returned by malloc to slope->slope_array, but to slope->slope_array[i]
slope->slope_array[i] = malloc(sizeof(int) * s);

Resources