strncpy is not working for me for the following variable. It is working fine elsewhere in the program.

char     szQName[21];
strncpy(szQName, "Text", 20);

//debugger shows szQName's value as -88D11B47-8F19-41CA-.

Has it ever happened to anyone?

Details (context of the code):

char     szQName[21];
LPSTR    szFileName;   //Long Pointer to a STRing (char*)

szFileName = malloc(256*sizeof(char));

GTGetUniqueFileName ("", "txt", "TXT", (LPSTR)szFileName);
//now szFileName = TXT-88D11B47-8F19-41CA-B586-9541BAD87CC4.txt

strncpy(szQName, "Text", 20);
//szQName = -88D11B47-8F19-41CA-

why?

Post a complete program which we can all compile, which produces the errors which you see.

There could be any number of reasons, anywhere in the code which could cause this effect. As soon as you trash memory, then anything can happen, including working for a while, producing garbage, then finally dying (as seems to be the case here).

Also, why are you casting in the call to GTGetUniqueFileName and do you have an online reference manual for it?

I'm sorry to say that posting the whole source code wouldn't help, 'cuz:

  • It's quite long
  • It cannot compile without 10s of header files & Oracle's JDEdwards Software.

But I can show you the contigious segment where the error occurs.
(I'm casting the LPSTR 'cuz I saw some other APIs doing the same. And no there is no reference manual (that I know of) for GTGetUniqueFileName() - neither online nor offline).

int     iMemorySize = 0;
int     iTotal = 0;
char*   pCursor;
void*   pHead;
char    szQName[21];
FILE*   pFile;
LPSTR   szFileName; //#define LPSTR char*

szFileName = malloc(30000*sizeof(char));

iMemorySize = 24+moTextSize; //moTextSize is int

pHead = malloc(iMemorySize);
pHead = memcpy (pHead, lpSource, 24+moTextSize);//lpSource points to a data structure

GTGetUniqueFileName ("", "txt", "TXT", (LPSTR)szFileName++);//szFileName is returned as "\TXT-somename-123.txt" hence the ++ to get rid of "\"

pFile = fopen (strcat("\\\\JDEDEP\\B7333\\MEDIAOBJ\\TEXT\\", szFileName), "w");
fprintf (pFile, szNewMessage);
fclose (pFile);

strncpy(szQName, "Text", 20);//szQName now equals "-somename-" instead of "Text"

If you think looking at the whole program would still help, you can look at the attachment.

Attachments
#include <jde.h>

#define b55try_c


/*****************************************************************************
 *    Source File:  b55try
 *
 *    Description:  Trial Business Function Source File
 *
 *        History:
 *          Date        Programmer  SAR# - Description
 *          ----------  ----------  -------------------------------------------
 *   Author 06/13/07    ASAEED      Unknown  - Created  
 *
 * Copyright (c) J.D. Edwards World Source Company, 1996
 *
 * This unpublished material is proprietary to J.D. Edwards World Source Company.
 * All rights reserved.  The methods and techniques described herein are
 * considered trade secrets and/or confidential.  Reproduction or
 * distribution, in whole or in part, is forbidden except by express
 * written permission of J.D. Edwards World Source Company.
 ****************************************************************************/
/**************************************************************************
 * Notes:
 *
 **************************************************************************/

#include <b55try.h>

/**************************************************************************
 *  Business Function:  UpdateAttachmentField
 *
 *        Description:  Update the attachments
 *
 *         Parameters:
 *           LPBHVRCOM           lpBhvrCom    Business Function Communications
 *           LPVOID              lpVoid       Void Parameter - DO NOT USE!
 *           LPDS                lpDS         Parameter Data Structure Pointer  
 *
 *************************************************************************/

JDEBFRTN (ID) JDEBFWINAPI UpdateAttachmentField (LPBHVRCOM     lpBhvrCom,
                                                 LPVOID        lpVoid,
                                                 LPDSD55001    lpDS)  
{
   /************************************************************************
    *  Variable declarations
    ************************************************************************/
   
   MATH_NUMERIC      mnSuppDataNumericKey1;
   MATH_NUMERIC      mnSuppDataNumericKey2;       
   JDEDB_RESULT      eJDEDBResult   = JDEDB_PASSED;
   DWORD             dwText         =285;
   char *            pszFixIt;
   int				 iAttachmentsCount = 0;
   unsigned long int i = 0;
   long int          iLen           = 0;
   char              szText[3000] = {'0'};
   char				 szNewMessage[3000] = {'0'};
   char				 szNewName[41] = {'0'};
   int				 iHistory[6][2];  /*[MOTYPE][0=EXISTS, 1=COUNT]*/

   /************************************************************************
    * Declare structures
    ************************************************************************/
   
   LPMOOBJECT		 lpMoObject;
   LPMOJDEOLE		 lpMoJdeOle;
   LPMOJDEIMAGE		 lpMoJdeImage;
   PTEXTBLOB		 pTextBlob;
   MOMISCDETAIL      MoMiscDetail;
   MOMISCHEADER      MoMiscHeader;
   PMOMISCHEADER     lpMoMiscHeader;
   LPKEY1_F0016D     lpdsKey;
   LPF0016D          lpDetail       = NULL;
   DSGT00092         dsGT00092Key;
   LPF9860           lpF9860;
   LPMOOBJECTINFO    lpMoObjectInfo;
   typedef struct tagALI {
	   MOBLOB			MoBlob;
	   char				szFirstText[171];
	   TEXTBLOB			TextBlob;
	   //MOJDEIMAGE		MoJdeImage[0];  //illegal
	   MOOBJECTINFO		MoObjectInfo[2];
   } ALI, *LPALI;
	ALI				 Ali;

   /************************************************************************
    * Declare pointers
    ************************************************************************/

   FILE				 *pFile;
   PSHORTCUTBLOB	 pShortcutBlob;
   PMOMISCDETAIL	 AttachmentItems   = { NULL };
   PMOMISCDETAIL     pMoMiscDetail;
   LPVOID            lpVoidPointer     = (LPVOID)NULL;
   HREQUEST          hRequest          = (HREQUEST)NULL;
   HUSER			 hUser		   	   = (HUSER)NULL;
   LPMOBLOB          lpMoBlob          = (LPMOBLOB)NULL;
   LPMOBLOB          lpMoBlob2       = (LPMOBLOB)NULL;
   LPSTR             lpText            = (LPSTR)NULL;
  /* LPCSTR            szPath          = "C:\\Documents and Settings\\asaeed\\Desktop";
   LPSTR             szExt             = "txt";
   LPSTR             szPrefix          = "TXT";
   */LPSTR            pStringKey       = (LPSTR)NULL;
   DWORD*             pdwText          = (DWORD *)NULL;

   /************************************************************************
    * Check for NULL pointers
    ************************************************************************/

   if ((lpBhvrCom == (LPBHVRCOM) NULL) ||
       (lpVoid    == (LPVOID)    NULL) ||
       (lpDS      == (LPDSD55001)	NULL))
   {
     jdeErrorSet (lpBhvrCom, lpVoid, (ID) 0, "4363", (LPVOID) NULL);
     return ER_ERROR;
   }

   /************************************************************************
    * Set pointers
    ************************************************************************/

   memset( (void *)(&dsGT00092Key),    (int)('\0'), sizeof(DSGT00092)       );
   memset( (void *)(&lpdsKey),         (int)('\0'), sizeof(LPKEY1_F0016D)   );
   memset( (void *)(&lpDetail),        (int)('\0'), sizeof(lpDetail)        );
   memset( (void *)(&lpMoBlob),        (int)('\0'), sizeof(LPMOBLOB)        );
   memset( (void *)(&lpMoBlob2),     (int)('\0'), sizeof(LPMOBLOB)        );
   memset( (void *)(&lpF9860),         (int)('\0'), sizeof(lpF9860)         );
   //memset( (void *)(&lpMoMiscHeader),  (int)('\0'), sizeof(lpMoMiscHeader)  );
   memset( (void *)(&MoMiscHeader),    (int)('\0'), sizeof(MoMiscHeader)    );
   memset( (void *)(&MoMiscDetail),    (int)('\0'), sizeof(MoMiscDetail)    );
   memset( (void *)(&lpMoObjectInfo),  (int)('\0'), 2*sizeof(lpMoObjectInfo)  );
   memset( (void *)(&lpVoidPointer),  (int)('\0'), sizeof(LPVOID)  );
   memset( (void *)(&lpMoJdeImage),  (int)('\0'), sizeof(LPMOJDEIMAGE)  );
   memset( (void *)(&lpMoJdeOle),  (int)('\0'), sizeof(LPMOJDEOLE)  );
   memset( (void *)(&lpMoObject),  (int)('\0'), sizeof(LPMOOBJECT)  );
   memset( (void *)(&pShortcutBlob),  (int)('\0'), sizeof(PSHORTCUTBLOB)  );
   memset( (void *)(&Ali),  (int)('\0'), sizeof(ALI)  );

   jdeAlloc (lpText, 100*sizeof(char), MEM_ZEROINIT);
   jdeAlloc (pStringKey, 100*sizeof(char), MEM_ZEROINIT);
   jdeAlloc (pdwText, 100*sizeof(DWORD), MEM_ZEROINIT);
   jdeAlloc (pszFixIt, 200*sizeof(char), MEM_ZEROINIT);

   lpMoMiscHeader = &MoMiscHeader;
   pMoMiscDetail = &MoMiscDetail;
   pdwText = &dwText;

   /************************************************************************
    * Initialize Behavior Routine (Open Database)
    ************************************************************************/
   
   eJDEDBResult = JDB_InitBhvr(lpBhvrCom, &hUser, (char *)NULL, JDEDB_COMMIT_AUTO);
   /* 3rd parameter,"Valid string pointer of active application.", is set to
   NULL | hUser is an output parameter */
   /* Check Initialize Behavior Success */
   if(eJDEDBResult != JDEDB_PASSED)
   {
      return ER_ERROR;
   }
   
   /************************************************************************
    * Main Processing
    ************************************************************************/

	strcpy (szNewMessage, "New Message to be taken as an input Parameter");
	strcpy (szNewName, "NewName");

/*--------------------------------------------------------------------------Check Previous Attachments*/
   strncpy (&(dsGT00092Key.szSupplementalDatabaseCode), "CL", 5);
   strncpy (&(dsGT00092Key.szTypeofData), "WO", 3);
   ParseNumericString(&dsGT00092Key.mnSuppDataNumericKey1, "211817");
   ParseNumericString(&dsGT00092Key.mnSuppDataNumericKey2, "0");

   pStringKey = AllocBuildStrFromDstmplName(NULL, "GT00092", &dsGT00092Key);
   pStringKey = StripKey (pStringKey);

   eJDEDBResult = JDEGTExists(lpBhvrCom->hEnv, (LPCSTR)"GT00092", (LPCSTR)pStringKey, (LPCSTR)"");
   if (eJDEDBResult != JDEDB_PASSED)									/*If No Previous Attachments */
   {
	   /*Get hRequest*/
	   eJDEDBResult = JDB_OpenTable(hUser, NID_F00165, ID_F00165_I00165, (NID *)NULL,
                                    (unsigned short)0, (char *)NULL,
									(HREQUEST)&hRequest);
	   strncpy (dsGT00092Key.szSupplementalDatabaseCode,   "CL", 5);
	   strncpy (dsGT00092Key.szTypeofData,                 "WO", 3);
	   ParseNumericString( &(dsGT00092Key.mnSuppDataNumericKey1), "211817");
	   eJDEDBResult = AddGenericTextName(hRequest, (LPSTR) "GT00092", (LPVOID)&dsGT00092Key, 
											  (LPSTR)szNewMessage);
	   JDB_CloseTable(hRequest);
   }   

/*--------------------------------------------------------------------------Fetch Blob */
   else
   {
	   eJDEDBResult = JDEGTAllocFetch (lpBhvrCom->hEnv, (LPCSTR)"GT00092", (LPCSTR)pStringKey, (LPCSTR)"", &lpDetail);
	   if (eJDEDBResult == JDEDB_PASSED)
	   {
		   int				iCount[6];
		   lpMoBlob = (LPMOBLOB)lpDetail->gdtxft.lpValue;

/*--------------------------------------------------------------------------Previous Attachments Present */
		   if (lpMoBlob->moTextSize == 0)                           /*If No previous Text*/
		   {
			   /*Get hRequest*/
			   eJDEDBResult = JDB_OpenTable(hUser, NID_F00165, ID_F00165_I00165, (NID *)NULL,
											(unsigned short)0, (char *)NULL,
											(HREQUEST)&hRequest);
			   strncpy (dsGT00092Key.szSupplementalDatabaseCode,   "CL", 5);
			   strncpy (dsGT00092Key.szTypeofData,                 "WO", 3);
			   ParseNumericString( &(dsGT00092Key.mnSuppDataNumericKey1), "211817");
			   eJDEDBResult = AddGenericTextName(hRequest, (LPSTR) "GT00092", (LPVOID)&dsGT00092Key, 
											  (LPSTR)szNewMessage);
			   JDB_CloseTable(hRequest);
		   }
/*--------------------------------------------------------------------------Text Attachments Exist */
		   else
		   {
			   int				iID = 0;
			   int				iMemorySize = 0;
			   int				iOffset = 0;
			   int				iTotal = 0;					
			   LPMOOBJECTINFO	lpMoObjectInfoReader;
			   TEXTBLOB			NewTextBlob;
			   char*			pCursor;
			   void*			pHead;
			   FILE*			pFile;
			   LPSTR			szFileName;
			   char				szQName[21];

			   //eJDEDBResult = JDEGTDelete (lpBhvrCom->hEnv, "GT00092", pStringKey, (LP

Try to comment out the suspicious code, like that containing GTGetUniqueFileName, and see whether it works then. To comment out you may use something like #if 0 and #endif Or, try to temporarily substitude the suspicious code with something not suspicious.

Already I see a whole host of problems coming out of the woodwork.
No wonder you're getting a myriad of obscure effects.

Essentially, you've been accumulating bugs without realising it. Now you have a bug-ridden large program and it's reached a critical mass where any attempt to add new code or fix a bug merely shows up another bug.

Here are some of the problems
> szFileName++ This was pointing at some allocated memory, but it isn't any more.
When you get around to free(szFileName) , you've introduced a bug into your memory allocator.

> strcat("\\\\JDEDEP\\B7333\\MEDIAOBJ\\TEXT\\", szFileName) String constants are supposed to be read-only, yet you're trying to append data to it. On real operating systems, this would cause an immediate segmentation fault.
On your machine, it just roams through memory getting longer and longer,
so "\\\\JDEDEP\\B7333\\MEDIAOBJ\\TEXT\\" becomes "\\\\JDEDEP\\B7333\\MEDIAOBJ\\TEXT\\foo" becomes "\\\\JDEDEP\\B7333\\MEDIAOBJ\\TEXT\\foofoo" becomes "\\\\JDEDEP\\B7333\\MEDIAOBJ\\TEXT\\foofoofoo" and so on until it eventually trashes some other memory.

String constants are initialised only ONCE (when the program is loaded). If you mess with them, they're changed for good. They're not automatically reset every time the line of code which refers to them is executed, so if your "Hello" has been trashed into "World" by the time you come to copy it, then "World" is what you'll get, no matter what the source code says.

So even though you may be doing strncpy(szQName, "Text", 20); , because "Text" is stored in the same kind of memory as the string you're abusing with strcat, you're going to end up with something completely different.

If this bug-rate is replicated in the rest of your large program, I'd be shocked that you got this far TBH.

Personally, given your use of strcat, and general pointer abuse, I would be recommending you re-learn C.

> I'm casting the LPSTR 'cuz I saw some other APIs doing the same.
Bad idea. Indiscriminate casting reduces the ability of the compiler to warn you when you're doing something wrong. If your code is correct, then you shouldn't need to cast it.

Thanks a bunch. My program works now. I just fixed my strcat - made a variable instead of concatenating the constant string.
I was wondering if free(--szFileName) would solve the issue. And yeah, you got that right. I really need to re-learn C.

This question has already been answered. Start a new discussion instead.