Help improving the code

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
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?

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
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.


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.


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.

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.


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.