debugging - Why do some C programs work in debug but not in release? -


ok,

so stuck here. have code program systematically executes people standing in circle based off algorithm, having problem crashing in release mode. code runs fine if run using debugger (codeblocks), if don't crashes. looked around online, , thing finding unintialized variables, tried setting values variables @ declaration , didn't fix problem.

if can see problem is, appreciate help.

#include<stdio.h> #include<stdlib.h> #include<string.h>  // if program not work, please run in debugger mode. work.  void remove_person(int** array, int arraysize, int position) {     int i;     (i = 0; < arraysize; ++i)         printf("%d ", (*array)[i]);     printf("\n");      int* temp = malloc((arraysize - 1) * sizeof(int)); // create temporary array smaller 1 element      memmove(temp,*array,(position+1)*sizeof(int)); // copy entire array before position      memmove(temp+position,(*array)+(position+1),(arraysize - position)*sizeof(int)); // copy entire array after postion      (i = 0; < arraysize - 1; ++i)         printf("%d ", (temp)[i]);     printf("\n");      free (*array);     *array = temp; }   int kill(int** a, int n) {     int pos = 0;     int round = 1;     while(n > 1)     {         pos = pos + 2 - (round % 2);          while(pos >= n)             pos = pos - n;          remove_person(a,n,pos);         n--;          while(pos >= n)             pos = pos - n;         round++;     }     return *a[0]; }  void main() {     int n, survivor, i;     int* people;      printf("enter number of people russian roulette: \n");     scanf("%d", &n);      people = (int*) malloc(n*sizeof(int));      for(i=0; < n; i++)     {         people[i] = i;     }      survivor  = kill(&people, n);     printf("the survivor person #%d\n", survivor); } 

the basic answer title question ("why c programs work in debug not in release?") "when invoke undefined behaviour".

here, in

memmove(temp,*array,(position+1)*sizeof(int)); // copy entire array before position  memmove(temp+position,(*array)+(position+1),(arraysize - position)*sizeof(int)); // copy entire array after postion 

you copy much. see why, observe first memmove copies temp[0], temp[1], ..., temp[position], , second copies temp[position], temp[position+1], ..., temp[position+arraysize-position-1] = temp[arraysize-1] (note overlap @ temp[position]). temp has space arraysize-1 elements -- copied 1 more allowed hold, undefined behaviour.

it works in debug not release mode because heap laid out differently (debug-mode allocators may pad allocations space catch bugs when running under debugger or profiler).


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -