Help improving the code

Jan 31, 2017 at 4:36pm
Hello All-

I need help improving the following code. This program converts input stream from ASCII to EBCDIC. It seems like this program is creating some memory errors while executing. Please see the code below-

#include <iostream>
#include <fstream>
#include <iconv.h>

int main(int argc, char *argv[])
{
FILE *fp;
fp = fopen("test.txt","w");
char src[] = "This is a test message.";
char dst[100];
size_t srclen = 24;
size_t dstlen = 24;

char * pIn = src;
char * pOut = ( char*)dst;

iconv_t conv = iconv_open("IBM500","ISO8859-1");
iconv(conv, &pIn, &srclen, &pOut, &dstlen);
iconv_close(conv);

fprintf(fp,"out: %s\n",dst);
fclose(fp);
}

I would really appreciate any help improving this program. Thanks in advance.

Regards,
Setu
Jan 31, 2017 at 6:03pm
Please use code tags when posting code.

The first thing I would recommend is that you start checking the values returned by those functions to insure they succeeded.

Next what makes you think there are some memory errors?

Jan 31, 2017 at 8:27pm
Thanks for your reply. Sorry about missing code tags in post.

The program works successfully. However when I use it in my application, it aborts after some time. The product support says it is related to program memory allocation and release.

I need help improving the pointer usage. Therefore I need help from the experts.

Thanks again.

Regards,
Setu
Jan 31, 2017 at 9:09pm
Did you run the program with your debugger? The debugger should be able to tell you exactly where it detects the problem, and you should be able to view the variables at the time of the crash and then start back tracing the problem to find the problem.


Jan 31, 2017 at 9:34pm
The program you posted looks reasonable. As jlb suggested, you should be testing for errors on all calls. iconv_open(), iconv() and iconv_close() can all return errors.

There's no way we can spot errors in your application without seeing your actual code.


Jan 31, 2017 at 10:29pm
Thanks jlb & AbstractionAnon for your comments.

It is much more complex than I could explain. However I have found a work around with environment setting so the program works with no aborts.

Still my concern here, have I used the pointers properly? Is there anyway I could possibly improve this code.

Thanks again.

Feb 1, 2017 at 3:25pm
Your use of pointers is correct. I might be tempted to eliminate pIn and pOut and write the call to iconv as:
 
  iconv(conv, &src, &srclen, &dst, &dstlen);


But that's purely a matter of style. A good optimizing compiler is going to optimize away pIn and pOut.


Feb 1, 2017 at 4:55pm
Thank you AbstractionAnon!

I have tried to implement your suggestion but still there are some errors. I will keep the existing program till I could find another way to implement the logic.

Thanks again.

Regards,
Setu
Topic archived. No new replies allowed.