c++ - Expression: _CrtlsValidHeapPointer(pUserData) error -


i'm trying learn pointers , first class objects in c++. i'm sure problem exists in pointer assignments or calls. wondering if me better understand pointers using static variables/methods.

firstclass.h

#pragma once  class firstclassobject {  public: firstclassobject();     firstclassobject(int);     firstclassobject(int, firstclassobject);     static void next_attr();     static int attribute;     int num;     firstclassobject *buffer;     firstclassobject *next;      ~firstclassobject(); }; 

firstclassobject.cpp

#include "firstclass.h" #include <stdlib.h> #include <string>  using namespace std;  firstclassobject::firstclassobject(){ num = attribute; next_attr(); };  firstclassobject::firstclassobject(int attr){     num = attr;     next_attr(); }  firstclassobject::firstclassobject(int attr, firstclassobject object){     num = attr;     next_attr();     buffer = (firstclassobject*) malloc(5);     memcpy(buffer,&object,1);     next = buffer; }  void firstclassobject::next_attr(){     attribute++; }  firstclassobject::~firstclassobject(){     free(buffer);     free(next); } 

firstclassobject_test.cpp

#include "firstclass.h" #include <iostream>  using namespace std;  int firstclassobject::attribute = 0;  firstclassobject get_next_object(firstclassobject object){     firstclassobject next_object;     next_object.buffer = object.next;     return next_object; }  int main(){      firstclassobject object;     firstclassobject otherobject(4, object);      cout << get_next_object(otherobject).num << "these numbers should same " << object.num << '\n';      return 0; } 

thanks in advance.

first , foremost, wrong:

buffer = (firstclassobject*) malloc(5); memcpy(buffer,&object,1); 

malloc() not same new[].

your firstclassobject type non-pod type since has non-trivial destructor. means cannot construct using malloc(). malloc() allocate memory, , that's it. need construct firstclassobject object, , using dynamically, use new[ ].

secondly, malloc() requires number of bytes allocate. sizeof(firstclassobject)? bet isn't 5 (the argument gave malloc()). main point if gave malloc() correct number of bytes, aren't constructing objects using it.

third, because firstclassobject non-pod, usage of memcpy() not good. in short, memcpy() does not copy objects. copy object, invoke copy constructor.

it looks you're reading c language books and/or reading c language resources, not c++ books , resources. if are, put down c bit , learn c++ proper sources. if attempt mix c c++ (without proper experience), wind issues such example.


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 -