Melvin Langvik Melvin Langvik - 3 years ago 399
C Question

Comparing pointers (char array) in C/C++

Having some issues comparing char arrays thru pointers. I am working without both the string library and iostream, would like to keep it that way.

char *GetCurrentPath()
{
char buffer[MAX_PATH];
if (!GetModuleFileNameA(NULL, buffer, MAX_PATH)) {
printf("GetModuleFileNameA failed, error: %d\n", GetLastError());
}
return (buffer);


}
char *GetInstallPath()
{
char buffer[MAX_PATH];
if (!SHGetSpecialFolderPathA(NULL, buffer, CSIDL_APPDATA, FALSE)) {
printf("SHGetSpecialFolderPathA failed, error: %d\n", GetLastError());
}
strcat(buffer, "\\service.exe");

return (buffer);
}



char *InstallPath = GetInstallPath();
char *CurrentPath = GetCurrentPath();

if (InstallPath == CurrentPath)......


The if statement causes an instant crash, same goes for strcomp.

Suggestions?

Answer Source

What you are currently doing is undefined behavior. The buffers that you are using in the two functions are defined locally to those functions and go out of scope the moment the functions end, giving you pointers to random stack addresses.

You need to either allocate the buffers in the functions:

Replace : char buffer[MAX_PATH];

With: char *buffer = new char[MAX_PATH]

Or pass allocated buffers from your main to the functions:

char *InstallPath = new char[MAX_PATH];
GetInstallPath(InstallPath);

And change your get path functions:

char *GetInstallPath(char *buffer)

In both cases, you will have to delete your pointers before ending your program to free up the memory.

On top of that, when you try to compare the two variables, they will compare pointer addresses rather than string contents. You will need to use strcmp() or something in that family of functions.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download