473,748 Members | 6,418 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

strncpy() and null terminated strings

Hi all! I support a rather large production EDI application with a
number of C programs, and I ran across a very interesting problem. I
have some code that used to work just fine for years, and now all of a
sudden it doesn't work any more. The input to the program did not
change at all (even ran it through a binary browser to make certain
there were no hidden chars or something strange) and the program has
not been recompiled in years.

In general, I know how to fix the problem but management here wants an
explanation as to why it ever worked to begin with. So I guess what
I'm looking for is some theories regarding what may have changed (OS,
memory configuration, etc.)

Here's the situation...

The program is reading a buffer that contains a string value. There
are no nulls in the string contained in the buffer (if that matters).
A strncpy() is being used to move substrings from the buffer into
variables, and then the variables are written to a report using
fprintf(). THE PROBLEM IS THAT THE STRINGS ARE NOT NULL TERMINATED
(and also not initialized with any values if that makes a difference
to you). Like I said earlier, this worked for years but all of a
sudden garbage is being outputted to the report unless I change the
program to null terminate the strings.

So I'm looking for theories as to why this ever worked to begin with
(actually that is what management here wants to know, and I'm having
trouble providing them with an explanation). Somehow these variables
must have been initialized with null values (or something like that)
and now they are not - so what could have changed to cause a
difference?

Here are some snippets of code from the program if it helps (I didn't
write this, I only keep it working):

....
<some code>
....

/* Global declaration */
struct FA_Table {
char CUST_ID[5];
char CUST_NAME[37];
char GS03[16];
char ISA05[3];
char GS02[16];
char newline;
};

....
<some code>
....

int Process_msga( fa, in, out)
register struct FuncAck *fa;
FILE **in, **out;
{
char TERM[3];
struct FuncAck tbl;

while ( fgets(buf, 256, *in ) != (char *)NULL )
{

if ( strncmp(buf, "ISA", 3)==0 ) {
TERM[0] = buf[3],
TERM[1] = '\n';
TERM[2] = '\0';

/* Below is the problem */
strncpy(fa->isa.ISA05,&b uf[32],2);
/*Adding fa->isa.ISA05[2]=0; here makes everything work ok*/
printf("found ISA05|%s|\n",fa->isa.ISA05);

....
<more code>
....
}
The printf above outputs the string + garbage unless I null terminate
the string. So any ideas why it ever worked to begin with???

Barry
Nov 14 '05 #1
4 4476
On 8 Apr 2004 06:39:05 -0700, ba*****@bellsou th.net (Barry) wrote:
Hi all! I support a rather large production EDI application with a
number of C programs, and I ran across a very interesting problem. I
have some code that used to work just fine for years, and now all of a
sudden it doesn't work any more. The input to the program did not
change at all (even ran it through a binary browser to make certain
there were no hidden chars or something strange) and the program has
not been recompiled in years.
<snip>
The program is reading a buffer that contains a string value. There
are no nulls in the string contained in the buffer (if that matters).
A strncpy() is being used to move substrings from the buffer into
variables, and then the variables are written to a report using
fprintf(). THE PROBLEM IS THAT THE STRINGS ARE NOT NULL TERMINATED
(and also not initialized with any values if that makes a difference
to you). Like I said earlier, this worked for years but all of a
sudden garbage is being outputted to the report unless I change the
program to null terminate the strings.


Some change in the execution environment, or a change in activity of
the program prior to the call, has made the memory used for automatic
allocation of your structure contain something other than zeros. (This
would be the stack on most common desktop and server platforms.)

It was luck that it ever worked.

--
Sev
Nov 14 '05 #2
Severian <se******@chlam ydia-is-not-a-flower.com> wrote:
Some change in the execution environment, or a change in activity of
the program prior to the call, has made the memory used for automatic
allocation of your structure contain something other than zeros. (This
would be the stack on most common desktop and server platforms.)


And just one example of how this _could_ come to pass: maybe your
application has been collecting data all these years, and this data has
finally grown so large that, in the course of the calculations, that
part of memory, which previously used to be newly allocated, now needs
to come from used and reclaimed memory blocks.

Richard
Nov 14 '05 #3
In <25************ *************@p osting.google.c om> ba*****@bellsou th.net (Barry) writes:
The printf above outputs the string + garbage unless I null terminate
the string. So any ideas why it ever worked to begin with???


Yes: the structure was initialised, by default and by accident with all
zeros. These zeros acted as string terminators. At some point, the
structure was no longer initialised with zeros, but with garbage. Now,
your "strings" were no longer null terminated and printf had no good
reason to stop at the intended place. The reason of the change is
external to the program (e.g. the new libraries coming with a new version
of the OS) and code that accidentally worked before no longer worked
after.

The easiest fix is to explicitly nullify all your data containers
(arrays, buffers, structures) before starting to fill them with
input data. Code that worked previously by accident will work now by
design, if you leave at least one byte untouched when storing the data
in your containers.

If the code wasn't supposed to handle strings, it should have used memcpy
instead of strncpy and *all* the %s conversion specifications should have
contained an explicit precision specification, i.e. %.2s for a data field
that is no longer than 2 characters.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #4

"Severian" <se******@chlam ydia-is-not-a-flower.com> wrote in

It was luck that it ever worked.

Bad luck. Seemingly correct behaviour is the most dangerous type of
undefined behaviour, as the Op's experience shows.
Nov 14 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2221
by: Simon | last post by:
Hi, I am a bit confused with zero based items and strncpy(...) assuming I have char str1 = "Hello world"; char str2; I now have str2 that should look something like
12
15690
by: ­m½Z | last post by:
I am a C programming beginner... I wonder, why strncpy(s, t, n) does not put '\0' at the end of the string. Because when I output the copied string, it output more than what I want, until I put '\0' at the end by myself. But, sometime I don't need put '\0' and it work well?? Like strncpy(s, t, n); strcat(s, t1); .....
4
323
by: Barry | last post by:
Hi all! I support a rather large production EDI application with a number of C programs, and I ran across a very interesting problem. I have some code that used to work just fine for years, and now all of a sudden it doesn't work any more. The input to the program did not change at all (even ran it through a binary browser to make certain there were no hidden chars or something strange) and the program has not been recompiled in years....
15
2147
by: ehabaziz2001 | last post by:
Hi, Till now I do not understand how the null character automatically added to the end of the string and it is not an element of the string array . All books said the null character (\0) added automatically to the end of the string. Let say char name="123456789" If entered the name in a loop;
12
1982
by: semut | last post by:
Given that the string is of null terminated type. What could be the possible causes (by experience) the string to have no null terminated and cause buffer overflow later. I know it is quite broad, just like to find out the causes as much as possible so that I could impose stricter checking toward my codes. note: I could not use std::string cause it will require a total rewrite. thanks.
43
4931
by: Frodo Baggins | last post by:
Hi all, We are using strcpy to copy strings in our app. This gave us problems when the destination buffer is not large enough. As a workaround, we wanted to replace calls to strcpy with strncpy. That is, replace calls to strcpy with say, my_strcpy(dest,src) which will internally find the destination buffer length. For this we need to know the destination buffer size. For statically allocated strings sizeof is returning the length of the...
9
3169
by: Ron | last post by:
#define MAX_SIZE 512 char mybuffer; void myfunction( const char* src ) { if( src == null ) { return; } /* A core dump is occuring here */ strncpy( mybuffer, src, MAX_SIZE );
4
5768
by: lurch132002 | last post by:
i am trying to create an array of structs to hold some information but whenever i get to the second element and try to strncpy it i get a segmenation fault. ive searched around for similar problems but i cant seem to figure out what im doing wrong. any help would be appreciated. #include <stdio.h> #include <stdlib.h> #include <string.h>
5
3815
by: davidcollins001 | last post by:
Hi, I am writing a small program to basically copy ls. I would like to copy a string so I thought I would use strncpy but I am getting the following error: I thought I would be able to debug this but i have been through the man pages and can't figure it out. Doing the same thing with strcpy works fine. The reason I wanted to use strncpy is because it is safe (as far as I am aware) I have seen a few posts to say that it doesn't guarantee...
0
8826
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9534
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9366
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9316
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6073
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4597
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3303
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2777
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2211
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.