I cannot figure out why this program is not working. I got Access Violation message when trying to push a variabel with the type of data is string to another variable that had allocated at memory with malloc.
For example, first I declare the variable..
string pName;
address temp;
After that, I call the Allocate module..
temp = Allocate(pName, 1, 1, 200);
And here's the module..
#include <...>
#include<string>
#define Info(T) (T)->info
#define FirstSon(T) (T)->ps_fs
#define NextBro(T) (T)->ps_nb
#define Parent(T) (T)->ps_pr
using namespace std;
typedef struct infoElmt{
string pName;
float number;
int type;
float price;
}compInfo;
typedef compInfo infotype;
typedef struct tElmtTree *address;
typedef struct tElmtTree {
infotype info;
address ps_fs, ps_nb, ps_pr;
} node;
typedef address DynTree;
address Allocate (string pName, float number, int type, float price) //(string pName, float number, int unit, int type, float price
{
address P;
P = (address) malloc (sizeof(node));
if (P != NULL)
{
Info(P).type = type;
Info(P).number = number;
Info(P).price = price;
FirstSon(P) = NULL;
NextBro(P) = NULL;
Parent(P) = NULL;
printf("OK");
Info(P).pName = pName;
}
return (P);
}
The error is came when the program run the Info(P).pName = pName; , I know it because if the printf("OK"); moved to below Info(P).pName = pName; , the "OK" doesn't showed in the console.
Is it problem with malloc and string?
Edit
- The
#include<..>is another Include like conio.h, etc. - I'm forget to put the
using namespace std;in the code..
#include <...>??? And the presence ofstringmakes this C++, a different language to C.std::stringis the only C++ I can find.mallocis pretty much deprecated,typedefing structs is no longer useful, objects shouldn't be passed by value when only reading them, and we havenullptr.malloc()and usenewinstead. If you're usingmalloc(), you should be writing C code.