Break point while trying to use free() to handle a dynamic array - c

The program triggers a break point on the free() function call.
Debugging the program returns this message:
HEAP[C_C.exe]: Heap block at 00498240 modified at 00498298 past requested size of 50
C_C.exe has triggered a breakpoint.
I don't understand why free() triggers the break point if all seems correct...
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
int* aloca_vetor(int control)
{
int *vetor;
vetor = (int *)malloc((control * sizeof(int)));
return vetor;
}
int main()
{
int *vetor;
int Input[2];
int testes;
int control;
int i, j, w = 0;
scanf("%d", &testes);
while (testes != 0)
{
scanf("%d%d", &Input[0], &Input[1]);
control = ((Input[1] - Input[0]) + 2);
vetor = aloca_vetor(control);
if (vetor == NULL)
{
printf("No memory!");
}
for (i = 2; i < control; i++)
{
vetor[i] = TRUE;
}
for (i = 2; i < control; i++)
{
if (vetor[i] == TRUE)
{
j = 0;
for (w = 0; j < (control - 1); w++)
{
j = i*i + w*i;
vetor[j] = FALSE;
}
}
}
for (i = 0; i < control; i++)
{
if (vetor[i] == TRUE)
{
printf("%d\n", i);
}
}
testes--;
free(vetor);
}
return 0;
}

I think that the problem arises in this loop
for (w = 0; j < (control - 1); w++)
{
j = i*i + w*i;
vetor[j] = FALSE;
}
It seems that the value calculated such a way as
j = i*i + w*i;
can be greater than control.
You could rewrite the loop like
for (w = 0; ( j = i*i + w*i ) < (control - 1); w++)
{
vetor[j] = FALSE;
}
Also in my opinion the loop
while (testes != 0)
{
//...
testes--;
free(vetor);
}
would be more readable if it would be rewritten the following way
while ( testes-- != 0 )
{
//...
free(vetor);
}
or
while ( testes-- )
{
//...
free(vetor);
}
Take into account that you wrote the program such a way that it seems nobody understands what it does.:) You should try to write programs more readable even if they are test programs.

j = i*i + w*i will become much larger than the last valid index for the array. Accesses beyond the borders of an array presents undefined behaviour.
One effect might be to overwrite memory used by the hep management, so the effect will only become visible when calling free.

Related

Passing an array to function a looping through it in C

I know I'm asking pretty basic question here, but could anyone give me a hint how to properly loop through an array which is initialized in another function ? I tried googling, found tons of videos but I didn't manage to get it right just yet. Would anyone please help me find out, what I'm missing in my code ? I'm a struggling beginner. Thanks in advance for your time.
My code (not functioning):
#include <stdio.h>
#define ARR_RANGE 1000000
#define GREATEST_NUMBER 1000000
void sieve(int eratosthenes[]);
int main()
{
int eratosthenes[ARR_RANGE];
int n = 999;
int c;
for(i = 2; i <= arrLen; ++i)
{
if(eratosthenes[i]!= -1)
{
int c = 0;
while(n % i == 0)
{
n /= i;
++c;
}
if(c >= 2)
{
printf("%d^%d x ", i, c);
}
else if(c == 1)
{
printf("%d x ", i);
}
}
else
continue;
}
return 0;
}
void sieve(int eratosthenes[])
{
for(int i = 1; i < GREATEST_NUMBER; ++i)
{
eratosthenes[i] = i;
}
for(int i = 2; i*i < GREATEST_NUMBER; ++i)
{
if(eratosthenes[i] != -1)
{
for(int j = 2*i; j < GREATEST_NUMBER ; j += i)
eratosthenes[j] = -1;
}
}
int arrLen = sizeof eratosthenes / sizeof eratosthenes[0];
}
In the main is not visible the call of function sieve,so the array is not passed into function, to do this you have to write in the main sieve(eratosthenes); (Passage by reference)

CriticalSection and Mutex locks work unexpectedly

I have been given the homework of making 5 threads as "philosophers" and each of them has to lock "eat" 2 synchronization locks simultaneously. Each thread must do this a million times.
The other part of this homework is to make the "philosophers" processes, and the locks mutex's.
I have made this code for the threaded part, and while it does technically work, the result isn't what I'd expect. The code has a logging system in which a red [NUM-x] means NUM thread attempted to lock two locks and failed to do so. And a green [NUM1-NUM2] means NUM1 thread successfully locked and unlocked 2 threads for the NUM2'd time.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <Windows.h>
#define CHOPSTICKS 5
#define PEOPLE 5
#define EAT_AMOUNT 1000000
#define MIN 2
#define INVALID -1
#define PAUSE printf("\n\n"); system("pause")
CRITICAL_SECTION chopsticks[CHOPSTICKS];
HANDLE chopsticksMutex[CHOPSTICKS]; // used for the mutex part of this question
VOID WINAPI eatThreadCritSect(LPVOID params) {
int index[MIN] = { 0 };
int usage = 0;
BOOL usageFlag = FALSE;
for (int i = 0; i < MIN; i++) {
index[i] = INVALID;
}
for (int i = 0; i < EAT_AMOUNT; i++) {
while (usage != MIN) {
for (int j = 0; j < CHOPSTICKS; j++) {
for (int k = 0; k < MIN && !usageFlag; k++) {
if (index[k] == j) {
usageFlag = TRUE;
}
}
if (!usageFlag) {
for (int k = 0; k < MIN && !usageFlag; k++) {
if (index[k] == INVALID) {
if (TryEnterCriticalSection(&chopsticks[j])) {
index[k] = j;
usage++;
}
usageFlag = TRUE;
}
}
}
usageFlag = FALSE;
}
for (int j = 0; j < MIN; j++) {
if (index[j] != INVALID) {
LeaveCriticalSection(&chopsticks[index[j]]);
index[j] = INVALID;
}
}
if (usage != MIN) {
printf("\x1b[31m[%d-X]", (int)params + 1); // CHOPSTICKS UNAVAILABLE
usage = 0;
}
}
printf("\x1b[32m[%d-%d]", ((int)params + 1), i + 1); // ATE SUCCESSFULLY
usage = 0;
}
}
void criticalEat() {
HANDLE hThreads[PEOPLE];
time_t begin = time(NULL);
for (int i = 0; i < PEOPLE; i++) {
hThreads[i] = CreateThread(NULL, 0, eatThreadCritSect, i, 0, NULL);
}
for (int i = 0; i < PEOPLE; i++) {
if (hThreads[i]) {
WaitForSingleObject(hThreads[i], INFINITE);
CloseHandle(hThreads[i]);
}
}
time_t end = time(NULL);
printf("\n\n\x1b[0mThey're now very saturated. It took them %llu seconds to eat with critical sections.", (end - begin));
}
void mutexEat() { // used for the mutex part of this question
PROCESS_INFORMATION hProcesses[PEOPLE];
CHAR name[] = "philosopher.exe 0";
time_t begin = time(NULL);
for (int i = 0; i < PEOPLE; i++) {
STARTUPINFO si;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
name[strlen(name) - 1] = i + '0';
CreateProcessA("philosopher.exe", name, NULL, NULL, FALSE, 0, NULL, NULL, &si, &hProcesses[i]);
}
for (int i = 0; i < PEOPLE; i++) {
WaitForSingleObject(hProcesses[i].hProcess, INFINITE);
CloseHandle(hProcesses[i].hThread);
CloseHandle(hProcesses[i].hProcess);
}
time_t end = time(NULL);
printf("\n\n\x1b[0mThey're now extremely fat and about to explode. It took them %llu seconds to eat with mutex's.", (end - begin));
}
int main() {
// used for the mutex part of this question
CHAR name[] = { "STICK_0" };
for (int i = 0; i < CHOPSTICKS; i++) {
name[strlen(name) - 1] = '0' + (i + 1);
InitializeCriticalSection(&chopsticks[i]);
chopsticksMutex[i] = CreateMutexA(NULL, FALSE, name);
}
criticalEat();
PAUSE;
mutexEat();
for (int i = 0; i < CHOPSTICKS; i++) {
DeleteCriticalSection(&chopsticks[i]);
if (chopsticksMutex[i]) { // preventing annoying warning
CloseHandle(chopsticksMutex[i]);
}
}
printf("\n\nI'm honestly surprised they made it. Why are we torturing philosophers?");
PAUSE;
return 0;
}
If I run this code, it will in a very technical sense work. However, the logged results show only green success logs, leading me to believe one of the lock checks is flawed. However, if I try to run the program in debug mode with breakpoints, and run it very slowly, red unsuccessful logs do appear. The same thing happens if I add a Sleep(1). Red logs appear. I believe red logs should appear regardless of these slowing measures, since 5 threads are trying to access 5 locks at the same time, each thread taking 2 locks for themselves.
As for the mutex part, here it is:
#include <Windows.h>
#include <stdio.h>
#define CHOPSTICKS 5
#define MIN 2
#define INVALID -1
#define EAT_AMOUNT 1000000
int main(int argc, char** argv) {
HANDLE chopsticksMutex[CHOPSTICKS];
int index[MIN] = { 0 };
int usage = 0;
BOOL usageFlag = FALSE;
CHAR name[] = { "STICK_0" };
for (int i = 0; i < CHOPSTICKS; i++) {
name[strlen(name) - 1] = '0' + (i + 1);
chopsticksMutex[i] = CreateMutexA(NULL, FALSE, name);
}
for (int i = 0; i < MIN; i++) {
index[i] = INVALID;
}
for (int i = 0; i < EAT_AMOUNT; i++) {
while (usage != MIN) {
for (int j = 0; j < CHOPSTICKS; j++) {
for (int k = 0; k < MIN && !usageFlag; k++) {
if (index[k] == j) {
usageFlag = TRUE;
}
}
if (!usageFlag) {
for (int k = 0; k < MIN && !usageFlag; k++) {
if (index[k] == INVALID) {
if (WaitForSingleObject(chopsticksMutex[j], 0) != WAIT_ABANDONED) {
index[k] = j;
usage++;
}
usageFlag = TRUE;
}
}
}
usageFlag = FALSE;
}
for (int j = 0; j < MIN; j++) {
if (index[j] != INVALID) {
ReleaseMutex(chopsticksMutex[index[j]]);
index[j] = INVALID;
}
}
if (usage != MIN) {
printf("\x1b[31m[%c-X]", argv[1][0] + 1); // CHOPSTICKS UNAVAILABLE
usage = 0;
}
}
printf("\x1b[32m[%c-%d]", argv[1][0], i + 1); // ATE SUCCESSFULLY
usage = 0;
}
return 0;
}
Now, from what I've been taught, Mutex locks, in general, are slower. But here again, there are no red logs indicating that there was a failed attempt to lock 2 locks, and the Mutex implementation is faster, even though it makes no sense.
Does what I'm saying even make any sense? In multi-threaded programming, should I expect this behaviour? I'm pretty sure I should expect a couple of red logs, without intentionally bottlenecking the program.

simulation algorithm implementation in C/C++

Let a row of 8000 lamps. Initially, only the one located to the left is lit.
Then, every second, the following operation is performed: each lamp changes state (on or off) if the one on its left was lit a second before. The leftmost lamp stays on all the time. This operation is instantaneous.
The process stops when the lamp at the right end lights for the first time.
How many lights are on?
My following implementation of the problem is false, can you help me?
#include <cstdio>
int t[8001][2];
int main()
{
t[1][0] = 1;
t[1][1] = 1;
int cpt1 = 0, ip = 0;
while (t[8000][0] != 1 && t[8000][1] != 1)
{
ip++;
for (int j=2;j<8001;j++)
{
if(t[j-1][!(ip&1)])
t[j][(ip & 1)] = !t[j][!(ip & 1)];
}
}
for(int j = 1;j < 8001; j++)
cpt1 += t[j][1];
printf("cpt=%d\n", cpt1);
}
Code is missing an update when the left does not change.
Code simplified (zero based offset, use of bool) and corrected below
#include<stdbool.h>
#include<stdio.h>
#define N 8000
bool t[N][2];
int main(void) {
t[0][0] = true;
t[0][1] = true;
int ip = 0;
while (t[N - 1][0] == 0 && t[N - 1][1] == 0) {
ip = !ip;
for (int j = 1; j < N; j++) {
if (t[j - 1][!ip]) {
t[j][ip] = !t[j][!ip];
} else {
t[j][ip] = t[j][!ip]; // add
}
}
}
int cpt1 = 0;
for (int j = 0; j < N; j++) {
cpt1 += t[j][1];
}
printf("N=%d cpt=%d\n", N, cpt1);
return 0;
}
Output
N=8000 cpt=2048
the following proposed code:
cleanly compiles
uses C header files rather than C++ header files
performs the desired operation, but not the fastest possible algorithm
is liberally commented
And now the proposed code:
#include <stdio.h>
int t1[8000]; // initially all zeros
int t2[8000];
int main( void )
{
// setup initial conditions
int numLitLights = 0;
t1[0] = 1;
// while stop condition not true
while ( t1[7999] != 1 )
{
// make one pass through lamps
// update values
for (int j=0; j<7999; j++)
{
if( t1[j] )
{
t2[j+1] = ( t1[j+1] )? 0 : 1;
}
}
// update original
for( int j=0; j< 8000; j++ )
{
t1[j] = t2[j];
}
}
// count lit lamps
for(int j = 0; j < 8000; j++)
{
if( t1[j] )
{
numLitLights++;
}
}
// output number of lit lamps
printf( "number of lit lamps: %d\n", numLitLights );
} // end function: main
The result (number of lamps lit) is
1024

How come my straight counter remains at a value of zero?

I am making a program in the C90 standard using GCC in Ubuntu 10.04, that randomly generates a hand of 5 card structs and calculates if the hand is a flush, straight, etc.
My function to calculate straights is:
int isStraight(card hand[]) {
int i, count = 1, result = 0;
for (i = 0; i < HAND_SIZE-1; i++) {
if (hand[i].pips == ((hand[i+1].pips) + 1)) {
count++;
}
}
if (count == HAND_SIZE)
result = 1;
return result;
}
My main function:
int main(void) {
int i, j;
int numHands = 0;
int flushCount = 0;
int straightCount = 0;
int xOfAKindCount = 0;
int straightFlushCount = 0;
int fullHouseCount = 0;
int isTwoPairCount = 0;
card deck[DECKSZ] = {0};
card hand[HAND_SIZE] = {0};
stack deckStack = {0};
stack handStack = {0};
initDeck(deck);
shuffleDeck(deck);
reset(&deckStack);
for (i = 0; i < DECKSZ; i++) {
push(deck[i], &deckStack);
}
do {
reset(&handStack);
for (i = 0; i < HAND_SIZE; i++) {
push(pop(&deckStack), &handStack);
if (isEmpty(&deckStack)) {
reset(&handStack);
shuffleDeck(deck);
reset(&deckStack);
for (j = 0; j < DECKSZ; j++) {
push(deck[j], &deckStack);
}
}
hand[i] = handStack.s[i];
}
numHands += 1;
arrangeHand(hand);
flushCount += isFlush(hand);
straightCount += isStraight(hand);
xOfAKindCount += isXOfAKind(hand, 2, 0);
straightFlushCount += isStraightFlush(hand);
fullHouseCount += isFullHouse(hand);
isTwoPairCount += isTwoPair(hand);
printf("Flushes:%d Straights:%d SF's:%d Number of Hands:%d\r",
flushCount, straightCount, straightFlushCount, numHands);
} while (1);
printf("\n");
return EXIT_SUCCESS;
}
My issue is my variable declared inside my function, result, is never set to 1 to indicate whether or not the hand is a straight, which therefore means my straightCount variable always remains at a value of zero. I do not have access to a debugger and in my mind the code I have makes sense. I'm new to programming in C, so if anybody could help me point out what is wrong with my function, I'd appreciate it. Thanks!
int isStraight(card hand[]) {
int step = 0;
for(int i = 1;i < HAND_SIZE; i++)
if(hand[i].pip != hand[i-1].pip+1)
/* Substitute step with i!=1 if over-edge invalid */
if(step || hand->pip != 1 || hand[i].pip != hand[i-1].pip+13-HAND_SIZE)
return 0;
else
step = 1;
return 1;
}
Right, after reading the code again, there are not enogh cards...
for (i = 0; i < HAND_SIZE-1; ++i)
Then you care counting pairs, not just individual cards, so
If (count == HAND_SIZE-1)
for (i = 0; i < HAND_SIZE-1; i++) { means that you are testing HAND_SIZE-1 pairs (which is correct), with i from from 0 to HAND_SIZE-2, so count will never be HAND_SIZE.
You just need to change your test to if (count == HAND_SIZE-1)
Assuming that (a) pip values are 1=Ace, 2=Deuce, ... and (b) the hand is sorted before being passed to the function, and (c) hands are exactly five cards, here's a quick one:
int isStraight(card hand[]) {
int i;
// Handle Broadway special case
if (hand[0].pips == 13 && hand[1].pips == 12 && hand[2].pips == 11 &&
hand[3].pips == 10 && hand[4].pips == 1) return 1;
// This will handle the rest
for (i = 0; i < (HAND_SIZE-1); i += 1) {
if (hand[i].pips != hand[i+1].pips) return 0;
}
return 1;
}
Also, I wouldn't use a structure for cards. Using a single integer is much faster and more versatile. Check out http://etceterology.com/blog/2013/5/23/representing-playing-cards-in-software

Expression cannot be evaluated. Malloc fail

I' having a problem allocating a structure in a function. Here is the code(I'm currently using visual studio 2008):
Mat3x3* ProdMat(Mat3x3 *m, Mat3x3 *n)
{
if(m == NULL || n == NULL)
{
cout << "\t[W] Cannot compute product of the two matrixes one or both are NULL." << endl;
return NULL;
}
Mat3x3 *p; // product
int i, j;
float sum = 0;
p = (Mat3x3*)malloc(sizeof(Mat3x3)); // <= Exp cannot be evaluated
for(i = 0; i < 3; i++)
{
for(j = 0; j < 3; j++)
{
sum = 0;
for(int k = 0; k < 3; k++)
{
float a = m->a[i][k];
float b = n->a[k][j];
sum += a * b;
}
p->a[i][j] = sum;
}
}
return p;
}
P contains a matrix with 9 entries. Here is the context in which the error is given:
Mat3x3* compute_final_trans(Trans **transes) // compute product of all transformation matrixes from right to left
{
int k_trans = 0, i, j;
Mat3x3 *final_trans;
if(transes == NULL)
{
printf("\t[E] Cannot compute sequence of NULL transformations.\n");
return NULL;
}
final_trans = (Mat3x3*)malloc(sizeof(final_trans));
for(i = 0; i < 3; i++) // generate eye matrix
for(j = 0; j < 3; j++)
{
if(i == j)
{
final_trans->a[i][j] = 1;
}
else
{
final_trans->a[i][j] = 0;
}
}
while(transes[k_trans++]);
for(i = k_trans - 2; i >= 0; i--)
{
final_trans = ProdMat(transes[i]->matrix, final_trans); // <= ERROR
}
return final_trans;
}
Final trans is initialised as the eye matrix and transes have been succesfully computed before this step(before calling compute_final_trans). The while is used to retreieve the number of transformations that transes contains. At line:
final_trans = ProdMat(transes[i]->matrix, final_trans);
ProdMat fails to allocate memory for p which is a pointer to a Mat3x3 structure.
perror suggests that there isn't enough memory to allocate to the structure. However I'm only using 1GB of RAM(4GB in all).
Any help/suggestion/reference will be very much appreciated.
Sebi
malloc(sizeof(final_trans))
This is bad. You are only allocating enough space for a pointer, not space for an array.

Resources