Criticize my code

Status
Not open for further replies.
I'm fairly involved with Multi Theft Auto: San Andreas, which is a multiplayer modification for Grand Theft Auto: San Andreas. I provide a lot of support on their forums, primarily for the client. I wrote a small console application in C++ called MTADiag to automatically update MTA to the latest nightly build, update DirectX if required, and gather some data diagnostically relevant data and merge the resulting info into one single text file that a user can copy and paste to PasteBin and link to on the forums. Here's an example:



I'm a relatively novice coder, so I was hoping you guys could criticize my code. The source can be found on Google Code here.
 

andrewme

Senator
7,120
Subscriptor
1. Your indentation is all messed up, because you've used a mix of tabs and spaces. Be consistent.

2. Curl.h:

Code:
#include "curl/curl.h"
#include "curl/types.h"
#include "curl/easy.h"

Nothing from these files is used in this header. Move the includes to Curl.cpp. You're polluting clients' namespaces.

Code:
bool downloadFile(char *fileURL, string filePath);

If this is supposed to be C++, why isn't fileUrl a string?

Code:
void progress_func(...);
size_t write_data(...);

These should not be in the header, since they're just internal helpers for downloadFile and not meant for use by clients. Remove these declarations (and copy them after the #include "Curl.h" line in Curl.cpp if you want to not worry about using the functions before they're defined.

3. Curl.cpp

Code:
bool downloadFile(char *fileURL, ...)
{
    char *url;
    url = new char[255];
    url = fileURL;
    ...

    curl_easy_setopt(curl, CURLOPT_URL, url);

    ...

    delete [] url;
}

This is completely wrong. For starters, you could simply eliminate the "url" variable and do "curl_easy_setopt(curl, CURLOPT_URL, fileURL);". Next, it's leaking memory - the "url = fileURL" line overwrites the result of the "new char[]" call, so your "delete[] url" call doesn't delete the allocation. What it actually tries to delete is the caller's memory - which may or may not be legal to delete with delete[] and is certainly none of this function's business (it may be a string literal, after all). You're lucky it's not crashing. Another option would be to change the type of fileURL to string and do "curl_easy_setopt(curl, CURLOPT_URL, fileURL.c_str());" - just like you do with "filePath". This would give a nice C++ API with no leaks or crashes.

Code:
res = curl_easy_perform(curl);

You never inspect the value of "res". Either inspect it, or eliminate the variable. Probably the right thing to do is inspect it and return true to the caller only if the download actually succeeded.

Regarding your variable declarations, this is C++, not C. They don't all have to be at the top of the function. Everything except "CURL *curl;" can move inside the "if (curl)" block.

Code:
size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
    size_t written;
    written = fwrite(ptr, size, nmemb, stream);
    return written;
}

This appears to be pointless. You should be able to delete it and just call "curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite);"

Code:
void progress_func(...)
{
}

You didn't write this. Unless you've worked out explicit permission from the author, Stack Overflow contributions are all Creative Commons Attribution Required.

Edit: and it looks like you probably derived downloadFunc from this: http://stackoverflow.com/questions/1636333
or this: http://siddhantahuja.wordpress.com/2009 ... g-libcurl/
 

JamesW

Ars Tribunus Militum
1,946
Subscriptor
Just looking at CDiag.

[*] Why are the members static?
[*] You use a fixed size buffer for GetEnvironmentVariable() and hope it's large enough. Call it with the size parameter set to zero and it will tell you what size buffer you require.
[*] CDiag::UpdateMTA() you new 'url' but don't destroy it. You don't need to new it anyway. Just set 'url = whichever MTA*NightlyURL'. Copying isn't needed. Make url a 'const char*'
[*] IsDirectXUpToDate() checks if a specific file is in a specific directory. Will it be there if a newer version is installed. DirectX must have a proper API for getting the version. Use it.
[*] CDiag::UpdateDirectX().

This:
Code:
char *dxWebSetupURL;
dxWebSetupURL = new char[97];
dxWebSetupURL = "http://download.microsoft.com/download/1/7/1/1718CCC4-6315-4D8E-9543-8E28A4E18C4C/dxwebsetup.exe";
.
delete[] dxWebSetupURL;
leaks 97 bytes. Do this instead:
Code:
const char* dxWebSetupURL = "http://download.microsoft.com/download/1/7/1/1718CCC4-6315-4D8E-9543-8E28A4E18C4C/dxwebsetup.exe";
// No need to call delete[].
[*] system() :scared:
[*] using namespace std; - Don't nobble the namespacing. Type out those std::'s!
 

andrewme

Senator
7,120
Subscriptor
util.cpp:

Code:
string readRegKey(string value, string subkey)
{
    ...

    char *cValue;
    char *cSubkey;
    cValue = new char[strlen(value.c_str())+1];
    cSubkey = new char[strlen(subkey.c_str())+1];                                                       
    
    strcpy (cValue, value.c_str());
    strcpy (cSubkey, subkey.c_str());                                                                   

    if ( RegOpenKey(HKEY_LOCAL_MACHINE, cSubkey, &hKey) == ERROR_SUCCESS)                               

    ...

    if ( RegQueryValueEx(hKey, cValue, 0, &dwType, (BYTE*)buf, &dwBufSize) == ERROR_SUCCESS)        

    ...

    delete [] cValue;
    delete [] cSubkey;                                                                           

    ...
}

This can all be replaced with:

Code:
if ( RegOpenKey(HKEY_LOCAL_MACHINE, subkey.c_str(), &hKey) == ERROR_SUCCESS)
...
if ( RegQueryValueEx(hKey, value.c_str(), 0, &dwType, (BYTE*)buf, &dwBufSize) == ERROR_SUCCESS)

* You don't call RegCloseKey() in the success path.

Code:
dwType = REG_SZ;
if ( RegQueryValueEx(hKey, cValue, 0, &dwType, (BYTE*)buf, &dwBufSize) == ERROR_SUCCESS)

This does not do what you think it does. "dwType" is an OUT parameter only, so there is no point to initializing it to REG_SZ. Further, RegQueryValueEx does not guarantee NUL-terminated strings. You should be using RegGetValue.
 
Thanks for the feedback everyone.

The disparity in tabs/spaces is due to Google Code sometimes screwing up the tabbing even though it looks correct in VS and in text editors. Is there a more elegant solution than converting tabs to spaces in cases where the spacing is affected?

CDiag's members are static because I have no need for multiple instances of the class. Is this bad practice?

I've removed the write_data function in Curl.cpp, used res to check whether things went smoothly, and replaced the progress_callback function. It's true that I had used that code on StackOverflow, but that was intended to be a temporary thing.

I've replaced the various functions which have char parameters with string as you guys suggested.

As far as I know, DirectXSetupGetVersion will only return the major version (i.e. 8.1, 9.0c, etc) and does not return whether the latest redistributable of DirectX is installed. Checking for D3DX9_43.dll in the system32 dir works well enough.

readRegKey uses RegGetValue now, thanks for the tip.

JamesW":3fg4u1v3 said:
You use a fixed size buffer for GetEnvironmentVariable() and hope it's large enough. Call it with the size parameter set to zero and it will tell you what size buffer you require.
Sorry, I don't quite understand - I tried calling it with the size parameter set to zero but there was no error or crash or anything. :confused:

The SVN on Google Code has been updated. Thanks for the criticism everyone. I'd welcome any other suggestions.
 

JamesW

Ars Tribunus Militum
1,946
Subscriptor
Ligushka":2mvzvo4r said:
JamesW":2mvzvo4r said:
You use a fixed size buffer for GetEnvironmentVariable() and hope it's large enough. Call it with the size parameter set to zero and it will tell you what size buffer you require.
Sorry, I don't quite understand - I tried calling it with the size parameter set to zero but there was no error or crash or anything. :confused:

Code:
char* buffer = 0;
// What size buffer do we need?
DWORD size = ::GetEnvironmentVariable("SystemRoot", buffer, 0);
if(size) {
  // We know the size now!
  buffer = new char[size];
  size = ::GetEnvironmentVariable("SystemRoot", buffer, size);
  assert(size);
} else {
  if(::GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
    // No such environment variable.
  } else {
    // WTF?
  }
}

if(buffer) {
  // Do stuff with buffer
  .
  .
  .
  delete[] buffer;
}
 
Thanks for the code example, makes sense now. However, I chose to store the environment variables into strings instead using getenv().

I use system() because I want to wait for a particular action to complete before continuing with the execution (i.e. wait for the latest nightly installer to finish, or DirectX to finish updating, or a dxdiag log to finish generating). What's so bad about using system()?

SVN updated again.
 
Status
Not open for further replies.