Link to home
Start Free TrialLog in
Avatar of KEFE
KEFE

asked on

C dll call freezes

I have the following two codes (C):
for a DLL:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

__declspec(dllexport) char* Echo(char* in) {
      char* out;
      out = "Sent: ";
      strcat(out, in);
      return(out);
}

And for an exe that calls the DLL:

#include <stdio.h>
#include <string.h>
#include <windows.h>

typedef char* (*EchoFunc)(char*);

int main(int argc, char *argv[]) {
      EchoFunc _EchoFunc;
      HINSTANCE hInstLibrary = LoadLibrary("Example.dll");
      if (hInstLibrary) {
            _EchoFunc = (EchoFunc)GetProcAddress(hInstLibrary, "Echo");
            if (_EchoFunc) {
                  char* in = "in test.";
                  fprintf(stdout, _EchoFunc(in));
            }
            FreeLibrary(hInstLibrary);
      } else {
            fprintf(stdout, "Example.dll Failed To Load!");
      }
      return 0;
}

Im using MingW TDM-GCC 5.9.2 32 bit for compilation, both files are produced without warnings or errors, but when I call the executable it freezes, I tried to use malloc too for the strings size in the DLL but didn't helped, can anyone help me with this?
Thank you in advance.
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Do you have debugging capabilities? If you step through with a debugger can you see where it freezes? Failing that - have you tried putting in output statements to see how far it gets?
Try this as your echo function, the array initializer list may not work if you are not using C++ 11. so remove that in case you get that as compilation error.
char* DLL_EXPORT Echo(char* in) {
    const char* const SentString  = "Sent: ";
    char* out = NULL;
    if(in!=NULL)
      out = new char[strlen(SentString) + strlen(in) + 1]{0};//If compilation error use without {0}
    else
      out = new char[strlen(SentString) + 1]{0};//if compilation error use without {0}
      //out = "Sent: ";
      strcpy(out, SentString);
    if(in)
      strcat(out, in);
      return(out);
}
Avatar of KEFE
KEFE

ASKER

Hello Karrtik, unfortunatlly this isn't C++ code, it is standard ANSI C.

Hello, Julian, I don't have debuging capabilities, but the executable exits with return 3221225477 (0xC0000005) which is STATUS_ACCESS_VIOLATION.
ASKER CERTIFIED SOLUTION
Avatar of Karrtik Iyer
Karrtik Iyer
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of KEFE

ASKER

Thank you very much, now it works, as I said I tried to use malloc but it seems I din't used it correctly, also I wasn't declaring the char variable correctly.
Thank you again for your help.