C++ heap corrupt -


int main() {     int = 3;     int arr[] = { 5, 3, 6 };     vect v(a, arr);     v.add(1);     v.add(2);     v.add(3);     v.add(4);     return 0; } 

vect class:

int n; int* ptr = new int[n]; 

constructor:

vect(int ninit, int arr[]) {     n = ninit;     (int = 0; < n; i++)     {         ptr[i] = tab[i];     } } 

add method in vect class:

 void add(int value)  {     n += 1;     ptr[n-1] = value;  } 

i'm getting error program.exe has triggered breakpoint. @ msvcr120d.dll!_heap_alloc_base(unsigned int size) line 58. i've tried using memcpy.

the interesting thing when call add once or twice, or when sending 1 int in arr array, okay.

what going wrong here?

main source of problem is:

void add(int value) {    n += 1;    ptr[n-1] = value; // danger !!!! } 

you're creating memory of size 'n' using new

  int* ptr = new int[n]; 

but in function void add(int value) you're trying store numbers in location out of allocated memory (problem).

solution 1:

if know maximum numbers want store in memory allocate of memory first using new , number of storing within allocated size.

solution 2:

if want store more number allocated allocate new memory using below function (note: copy old content new memory , delete old/new allocated memory after use avoiding memory leaks.)

void  vect::resize(int newsize ) {          int* newarr = new int[newsize];       memcpy( newarr, ptr, n * sizeof(int) );       n = newsize;       delete [] ptr;       ptr = newarr; } 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -