free() crashes the code - c

#include <stdio.h>
#include <stdlib.h>
void printingArr(int** arr, int rows);
void sortingEachOneOfThem(int** pArr, int rows);
void sortingTheWholeArray(int** pArr, int rows);
void bubbleSort(int* arr);
void freeArray(int **a, int m);
int main(void)
{
int** pArr = 0;
int numOfRows = 0;
int sizes = 0;
printf("Enter number of rows: ");
scanf("%d", &numOfRows);
pArr = (int**) malloc(sizeof(int*) * numOfRows);
if (pArr == NULL)
{
printf("Unsuccessful malloc!\n");
return 1;
}
for (int i = 0; i < numOfRows; i++)
{
printf("Enter array length for row %d: ",i);
scanf("%d", &sizes);
pArr[i] = (int*) malloc(sizeof(int) * sizes + 1);
if (pArr[i] == NULL)
{
printf("Unsuccessful malloc!\n");
return 1;
}
pArr[i][0] = sizes;
for (int k = 1; k < sizes + 1; k++)
{
printf("Enter value for array: ");
scanf("%d", &pArr[i][k]);
}
}
printingArr(pArr, numOfRows);
sortingEachOneOfThem(pArr, numOfRows);
printingArr(pArr, numOfRows);
sortingTheWholeArray(pArr, numOfRows);
printingArr(pArr, numOfRows);
for (int i = 0; i < numOfRows; i++)
{
if (pArr[i] != NULL)
{
free(*(pArr + i));
}
}
//free(pArr);
system("pause");
return 0;
}
/*
this amazing, wonderfull piece of program prints the array given
input: int** arr, int rows
output: none
*/
void printingArr(int** arr, int rows)
{
int i = 0;
int k = 0;
for (i = 0; i < rows; i++)
{
for (k = 0; k <= arr[i][0]; k++)
{
printf("%d ", arr[i][k]);
}
printf("\n");
}
printf("\n");
}
/*
This beautiful function sorts the whole array, but its length of rows like a pyramid
input: int** arr, int rows
output: none
*/
void sortingTheWholeArray(int** pArr, int rows)
{
int* temp = 0;
int i = 0, k = 0;
for (i = 0; i < rows - 1; i++)
{
for (k = 0; k < rows - 1; k++)
{
if (pArr[k][0] > pArr[k + 1][0])
{
temp = pArr[k];
pArr[k] = pArr[k + 1];
pArr[k + 1] = temp;
}
}
}
}
/*
This little small function sorts every row of the array of arrays given to it
input: int** arr, int rows
output: none
*/
void sortingEachOneOfThem(int** pArr, int rows)
{
int i = 0;
for (i = 0; i < rows; i++)
{
bubbleSort(pArr[i]);
}
}
/*
This little piece of a code is a bubble sort, sorts the array given to it :)
input: int* arr, int rows
output: none
*/
void bubbleSort(int* arr)
{
int i = 1, k = 0;
for (i = 1; i < arr[0] - 1; i++)
{
for (k = 1; k <= arr[0] - i; k++)
{
if (arr[k] > arr[k + 1])
{
arr[k] += arr[k + 1];
arr[k + 1] = arr[k] - arr[k + 1];
arr[k] -= arr[k + 1];
}
}
}
}
the free at the end crashes my code, showing this error:
https://i.stack.imgur.com/nqxBG.png
the same usage of the function free() on another code worked good, but not here. I have tried running through it in step by step mode, it crashes at the first free. Dr. memory shows this: https://i.stack.imgur.com/rSZJr.png
another link: https:// i.stack. imgur.com/ZX2Ne.png (paste it without the spaces in the middle, Can't post more than 2 links)
what can I do?

This:
pArr[i] = (int*) malloc(sizeof(int) * sizes + 1);
under-allocates. Adding a single byte to the size of an array of int makes little sense. You probably meant:
pArr[i] = malloc((sizes + 1) * sizeof *pArri[i]);
Don't cast the return value of malloc(), and use sizeof on the left-hand side.

Related

arrange the array in an order such that the even values are followed by odd values in the array

this is the program I made ,if I input [13,11,10,17,18] i get the output [12,13,17,11,10]. I do not understand what mistake I am making. somebody please help me understand.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n,j,i,num,v;
printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %d\n", n);
ptr = (int*)malloc(n * sizeof(int));
for (i = 0; i < n; ++i) {
scanf("%d",&v);
ptr[i] = v;
}
i=0;
j=0;
while(i<5){
j++;
if (ptr[j]%2==0 && i%2==0){
num=ptr[i];
ptr[i]=ptr[j];
ptr[j]=num;
}
if (ptr[j]%2!=0 && i%2 !=0){
num=ptr[i];
ptr[i]=ptr[j];
ptr[j]=num;
}
if (j==4){
i++;
j=0;
}
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
Ok, I tried to tell you how you should have written you program, but you didn't listen:
Make a https://stackoverflow.com/help/minimal-reproducible-example
A MCVE needs all the includes
No interactive stuff. You need to run and run and run your program in a debugger. You don't want to put data in manually every single time.
You want many tests, and you want to repeat them, so that when you fix one, you don't break another.
Make a function which does the job.
Free your memory!
Now to the solution: your idea of a solution was fine apart from the stuff about indexes. It's pretty similar to the one you will find down here. The only difference is that I put the odd numbers al the end to avoid checking elements multiple times.
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
void evenodd(int *v, size_t n)
{
for (size_t i = 0; i < n; ++i) {
while (i < n && v[i] % 2 == 0) {
++i;
}
--n;
while (i < n && v[n] % 2) {
--n;
}
if (i < n) {
int tmp = v[i];
v[i] = v[n];
v[n] = tmp;
}
}
}
bool is_evenodd(int *v, size_t n)
{
size_t i = 0;
while (i < n && v[i] % 2 == 0) {
++i;
}
while (i < n && v[i] % 2 != 0) {
++i;
}
return i == n;
}
void main_test(const int *v, size_t n)
{
int *v1 = memcpy(malloc(n * sizeof(int)), v, n * sizeof(int));
evenodd(v1, n);
if (is_evenodd(v1, n)) {
printf("Ok!\n");
}
else {
printf("Fail!\n");
}
free(v1);
}
int main(void)
{
main_test((int[]) { 1 }, 0);
main_test((int[]) { 1 }, 1);
main_test((int[]) { 2 }, 1);
main_test((int[]) { 1, 2 }, 2);
main_test((int[]) { 1, 3 }, 2);
main_test((int[]) { 2, 1 }, 2);
main_test((int[]) { 2, 4 }, 2);
main_test((int[]) { 1, 3, 2 }, 3);
main_test((int[]) { 1, 4, 2 }, 3);
size_t n = 1000;
int *a = malloc(n * sizeof *a);
for (size_t i = 0; i < n; ++i) {
a[i] = rand();
}
main_test(a, n);
free(a);
return 0;
}
You can try the following code :
int even_index = 0; //start index
int odd_index = 4; //end index
for(int i=0;i<5;i++){
if(ptr[i] % 2 == 0){
int temp = ptr[even_index];
ptr[even_index++] = ptr[i]; //swapping values and incrementing even_index
ptr[i] = temp;
}else{
int temp = ptr[odd_index];
ptr[odd_index--] = ptr[i];
ptr[i] = temp;
}
}
or you can also count the number of even numbers in the digits during input and assign odd_value = even_num // number of even digits
ok so I solved it....
see the even numbers always end up in even indexes so we need to set a pointer on those even index(current index) and search for any even number after the current index.
if we find any(even number) we swap the current index value with the even number.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n,j,i,num,v;
printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %d\n", n);
ptr = (int*)malloc(n * sizeof(int));
for (i = 0; i < n; ++i) {
scanf("%d", &v);
ptr[i] = v;
}
i=0;
j=0;
while(i<n && j<n){
if (ptr[j]%2==0){
num=ptr[i];
ptr[i]=ptr[j];
ptr[j]=num;
i+=2;
j=i;
}
j++;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
If this problem is to sort an array in order (descending) and then further place all even values before odd values I would recommend:
Sort the array
Swap and shift any odd numbers with the even numbers
Here's a naive implementation:
for (int i = 0; i < len - 1; i++) {
for (int j = i + 1; j < len; j++) {
if (arr[i] < arr[j]) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
int lastEven = 0;
for (int i = 0; i < len - 1; i++) {
if (arr[i] % 2 && (arr[i + 1] % 2 == 0)) {
tmp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = tmp;
lastEven = i;
} else if (arr[i] % 2 == 0 && lastEven-i > 1) {
for (int j = i; j > lastEven; j--) {
tmp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = tmp;
}
lastEven++;
}
}
Given the input [13,11,10,17,18] this will first sort the array ([18,17,13,11,10]) then separate the evens and odds ([18,10,17,13,11])

Weird behaviour when merge sorting an array

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <time.h>
void DISPLAY(int*, int);
int* MERGE(int*, int, int* , int, int* , int );
int* MERGESORT(int* , int );
int main()
{
int* array = NULL;
array = (int*) malloc(7 * sizeof(int) );
array[0] = 10;
array[1] = 9;
array[2] = 8;
array[3] = 57;
array[4] = 6;
array[5] = 5;
array[6] = 24;
printf("\nOriginal array: \n");
DISPLAY(array, 7);
array = MERGESORT(array, 7);
printf("\n\nResulting array: \n");
DISPLAY(array, 7);
}
void DISPLAY(int* array, int size)
{
int i;
for(i = 0; i < size; i++){
printf("%d ", array[i]);
}
}
int* MERGESORT(int *array, int size) {
if(size < 2)
return array;
int mid = size / 2;
int rightsize = size-mid;
int* L = (int*) malloc(mid * sizeof(int));
int* R = (int*) malloc((size-mid) * sizeof(int));
int i;
for(i = 0; i < mid; i++)
L[i] = array[i];
for(i = mid; i < size; i++)
R[i-mid] = array[i];
L = MERGESORT(L, mid);
R = MERGESORT(R, size-mid);
array = MERGE(array, size, L, mid, R, rightsize);
free(L);
free(R);
return array;
}
int* MERGE(int *array, int size, int *L, int leftsize,int *R, int rightsize) {
int i, j, k;
i = 0;
j = 0;
k = 0;
while(i < leftsize && j < rightsize)
{
if(L[i] < R[j])
{
array[k] = L[i];
i++;
}
else{
array[k] = R[j];
j++;
}
k++;
}
while(i < leftsize)
{
array[k] = L[i];
i++;
k++;
}
while(j < rightsize)
{
array[k] = L[j];
j++;
k++;
}
printf("\nUpdated array: \n");
DISPLAY(array, size);
return array;
}
Hello, I have a problem when I try to perform merge sorting in an array. Some items in the array are printing weird. Every time the arrays get updated, the value gets printed out, but it doesn't work at specific inputs.
When I input small numbers (like 1-2 digits), then the array gets sorted normally.
Sample run of program sorting incorrectly:
https://i.stack.imgur.com/OLg0b.png
while(j < rightsize)
{
array[k] = L[j];
j++;
k++;
}
should be
while(j < rightsize)
{
array[k] = R[j];
j++;
k++;
}
Umm, sorry for wasting time on such a simple mistake.
Consider.
int* R = (int*) malloc((size-mid) * sizeof(int));
(which ought to be written int *R = malloc((size - mid) * sizeof *R);)
What is the highest valid index in that array? Trying to read from (or write to) R[n] for n > size - mid - 1 invokes undefined behavior.

Difference between malloc and calloc in this case?

This is a code for multiplying two square matrices in C.
What is the difference between using malloc and calloc in void multiply() function?
When using malloc, I am getting garbage values, but calloc is providing the right answer.
Only the first row is outputting garbage values so is it an issue with the way malloc allocates space in the heap as compared to calloc?
#include <stdio.h>
#include <stdlib.h>
int *getArray(int);
void display(int *, int, int);
void multiply(int *, int *, int);
int main() {
int n;
printf("enter dimension of square matrix:\n");
scanf("%d", &n);
int *arr1;
int *arr2;
arr1 = getArray(n);
display(arr1, n, n);
printf("\n now give input for next array");
arr2 = getArray(n);
display(arr2, n, n);
printf("\n\n\n");
multiply(arr1, arr2, n);
return 0;
}
int *getArray(int n) {
int *arr = (int *)malloc(n * n * sizeof(int));
printf("\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", (arr + i * n + j));
}
}
/*for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf(" %d ", *(arr + i * n + j));
}
printf("\n");
}*/
return arr;
}
void display(int *arr, int row, int col) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
printf(" %d ", *(arr + i * row + j));
}
printf("\n");
}
}
void multiply(int *arr1, int *arr2, int n) {
int *arr = (int *)calloc(n * n, sizeof(int));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
*(arr + i * n + j) += (*(arr1 + i * n + k)) * (*(arr2 + k * n + j));
}
}
}
printf("product of above matrices = \n\n");
display(arr, n, n);
}
The only functional difference between allocating memory with malloc() and with calloc() for the same size, assuming the size computation is accurate, is the latter initializes the block to all bits 0, whereas the former does not.
All bits 0 means all int values in the array are initialized to 0.
The inner loop in the multiply function only increments the element at row i and column j, therefore the function relies on implicit initialization of the array elements to 0. calloc() does that, but not malloc() so you definitely need to use calloc().
Also note these remarks:
in display the computation for the offset of the matrix element at row i column j should be printf(" %5d ", *(arr + i * col + j));
multiply should return arr and display() should be called in the main function.
you should check for scanf(), malloc() and calloc()` failure
you should free allocated memory
pointer arguments to objects that are not modified by the function should be const qualified so the function can be called with a pointer to a const object.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
int *getArray(int);
void display(const int *, int, int);
int *multiply(const int *, const int *, int);
int main() {
int n;
printf("enter dimension of square matrix:\n");
if (scanf("%d", &n) != 1)
return 1;
printf("\n now give input for the first array");
int *arr1 = getArray(n);
if (!arr1)
return 1;
display(arr1, n, n);
printf("\n now give input for the second array");
int *arr2 = getArray(n);
if (!arr2)
return 1;
display(arr2, n, n);
printf("\n\n\n");
int *arr = multiply(arr1, arr2, n);
if (!arr)
return 1;
printf("product of above matrices = \n\n");
display(arr, n, n);
free(arr1);
free(arr2);
free(arr);
return 0;
}
int *getArray(int n) {
int *arr = malloc(sizeof(int) * n * n);
if (arr == NULL)
return NULL;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (scanf("%d", (arr + i * n + j)) != 1) {
free(arr);
return NULL;
}
}
}
return arr;
}
void display(const int *arr, int row, int col) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
printf(" %5d ", *(arr + i * col + j));
}
printf("\n");
}
}
int *multiply(const int *arr1, const int *arr2, int n) {
int *arr = calloc((size_t)n * n, sizeof(int));
if (arr == NULL)
return NULL;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
*(arr + i * n + j) += (*(arr1 + i * n + k)) * (*(arr2 + k * n + j));
}
}
}
return arr;
}

Implementing a count sort is crashing my program every time, cannot spot malloc/free error

I've been stuck on this for a while and absolutely cannot find a solution to my problem. I following along Sedgewick's algorithms in C to implement a count sort, but for some reason my b array is not reading the values of my input array correctly, and also crashes the program when trying to free. Any help will be appreciated.
void count_sort(int* a, int l, int r, int M)
{
int i, j;
int* cnt = (int*)malloc(M * sizeof(int));
if (!cnt) {
printf("Returned NULL PTR for cnt\n");
exit(1);
}
int* b = (int*)malloc((r + 1) * sizeof(int));
if (!b) {
printf("Returned NULL PTR for b\n");
exit(1);
}
printf("\n\n\n");
for (j = 0; j < M; ++j)
cnt[j] = 0;
for (i = l; i <= r; ++i)
cnt[a[i]]++;
for (i = 1; i < M; ++i)
cnt[i] += cnt[i - 1];
/*
free(b);
free(cnt);
printf("Able to free here\n");
exit(0);
*/
for (i = l; i <= r; ++i) {
b[cnt[a[i]]] = a[i];
printf("%d\n", b[cnt[a[i]]]);
++cnt[a[i]];
}
/*
free(b);
free(cnt);
printf("Able to free here\n");
exit(0);
*/
for (i = l; i <= r; ++i)
a[i] = b[i - l];
free(cnt);
free(b);
}
int is_sort(int* a, int N)
{
int i;
for (i = 0; i < N - 1; ++i) {
if (a[i + 1] < a[i]) {
printf("%d %d\t%d %d\n", i, a[i], i + 1, a[i + 1]);
return 0;
}
}
return 1;
}
int main(int argc, char** argv)
{
srand(time(NULL));
rand();
int N = atoi(argv[1]);
int M = atoi(argv[2]);
int* arr = (int*)malloc(N * sizeof(int));
int i;
for (i = 0; i < N; ++i) {
arr[i] = ((int)(1000 * (1.0 * rand() / RAND_MAX))) % M;
printf("%d\n", arr[i]);
}
count_sort(arr, 0, N - 1, M);
if (is_sort(arr, N))
printf("sorted\n");
else
printf("not sorted");
free(arr);
return 0;
}
The issue lies in these lines:
for (i = l; i <=r; ++i) {
b[cnt[a[i]]] = a[i];
printf("%d\n", b[cnt[a[i]]]);
++cnt[a[i]];
}
You want to decrement cnt[a[i]], not increment and also you want to do it before the assignment b[cnt[a[i]]] = a[i];, not after.
With these modifications the code works correctly.

C_(visual)_Debug Error_ Run-Time Check Failure #2 -S

I want to reverse numbers of array,
but I can't understand why it didn't run.
Thanks for explaining what does Debug Error_ Run-Time Check Failure #2 -S mean..
Thanks,
#include <stdio.h>
int main()
{
int arr[] = { 1,2,3,4,5 };
int size, i, j;
int temp = 0;
size = sizeof(arr) / sizeof(arr[0]); //use this for changing size
printf("first_array :");
for (i = 0; i < size; i++)
{
printf("%d", arr[i]);
}
printf("\n");
for (i = 0; i <= (size / 2); i++)
{
j = size - i;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
printf("Riv_array :");
for (i = 0; i < size; i++)
{
printf("%d", arr[i]);
}
return 0;
}
Array index starts from 0 in C and your array has 5 elements so arr[4] is the last element but your code:
j = size - i;
arr[j];
when i=0 access to arr[5], this is your code error: Array index out of bound.
you should use j = size - i-1; to point to the last element of array, not j = size - i;
see this working sample (your sample code with some edit):
#include <stdio.h>
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
int size, i, j;
int temp = 0;
size = sizeof(arr) / sizeof(arr[0]); //use this for changing size
printf("first_array :");
for (i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
for (i = 0; i <= (size / 2); i++)
{
j = size - i - 1;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
printf("Riv_array :");
for (i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
another way to reverse array using pointers:
#include <stdio.h>
void reverse(int* p, int count){
int temp;
int* q = p + count - 1; // point to the end
count /= 2;
while (count--) {
temp = *p;
*p++ = *q;
*q-- = temp;
}
}
void print_array(int *p, int count){
while (count--) printf("%d ", *p++);
printf("\n");
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
int count = ((&arr)[1] - arr);
print_array(arr, count);
reverse(arr, count);
print_array(arr, count);
return 0;
}
output:
1 2 3 4 5
5 4 3 2 1

Resources