473,799 Members | 3,026 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Undefined Behavior

Why would this code cause undefined behavior?

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

#define TRUE 1
#define FALSE 0
#define MAX_PASSWORD 11
int loop;
unsigned char rx;
int _strlen(s)
unsigned char s[];
{
int i;

i=0;
while(s[i]!='\0')
++i;
return i;
}

int encrypt (s, x, len)
unsigned char *s ;
unsigned char x;
int len;
{

int i,ok;
unsigned char seed_1,seed_2;

seed_1 = rx;
seed_2 = rx + 31;
ok = TRUE;
for(i = 0 ; i < len ; i++)
{
seed_1 -= i;
seed_2 += i;
if(i%2 != 0)
s[i] -= seed_1;
else
s[i] += seed_2;
if(s[i] == '&' || s[i]== '\0' || s[i] == '\n')
ok = FALSE;
}
if (x == '&')
ok = FALSE;
return ok;
}

int decrypt (s, len)
unsigned char *s;
int len ;

{
unsigned char seed_1, seed_2;
int i;

seed_1 = rx;
seed_2 = rx+31;
for (i = 0; i < len ; i++)
{
seed_1 -= i;
seed_2 +=i;
if (i % 2 != 0)
s[i] += seed_1;
else
s[i] -= seed_2;
}
return TRUE;
}

int encrypt_string (s)
unsigned char *s ;
{

unsigned char x;
int c, len;

x=0;
c=FALSE;
len= _strlen(s);

while( c!= FALSE || loop>0)
{
x++;
c=encrypt(s, x, len);
loop--;
}
s[len++] = x;
s[len++] = rx;
s[len]= '\0';

return TRUE;
}
int decrypt_string( s)
unsigned char *s;
{

unsigned char x,y ;
int len;

len = _strlen(s)-1;

rx= s[len];
len--;
x=s[len];
for(y = 0; y < x ; y++)
decrypt(s, len);
s[len]= '\0';

return TRUE;
}
int main() {

unsigned char *s;
unsigned char endchar;
unsigned int y;
int len;
s=(unsigned char *) calloc( MAX_PASSWORD, sizeof(unsigned char) );
if(s==NULL){
printf("Could not allocate Memory");
return 0;
}

fgets(s,MAX_PAS SWORD,stdin);
len=_strlen(s);

endchar =s[len-1];

if(endchar=='\r ' || endchar=='\n')
s[len-1]='\0';

rx=strlen(s) ;
loop=1;

y=encrypt_strin g(s);

if(y==TRUE)
printf("\n\nEnc rypted String :%s ######%d\n\n",s ,_strlen(s));

y=decrypt_strin g(s);
if(y==TRUE)
printf("Decrypt ed String: %s %d\n",s,_strlen (s));

if(*s=!NULL){
free(s);
s=NULL;
}
else
printf("Could not deallocate memory\n");
return 0;

}

Apr 25 '07 #1
13 1290
bb****@gmail.co m said:
Why would this code cause undefined behavior?

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

#define TRUE 1
#define FALSE 0
#define MAX_PASSWORD 11
int loop;
unsigned char rx;
int _strlen(s)
Invading implementation namespace.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Apr 25 '07 #2
In article <11************ **********@r35g 2000prh.googleg roups.com>,
<bb****@gmail.c omwrote:
>#define MAX_PASSWORD 11
s=(unsigned char *) calloc( MAX_PASSWORD, sizeof(unsigned char) );
if(s==NULL){
printf("Could not allocate Memory");
return 0;
}

fgets(s,MAX_PAS SWORD,stdin);
len=_strlen(s);
What's this _strlen()? Apart from anything else, that's a reserved
name.
>
endchar =s[len-1];

if(endchar=='\r ' || endchar=='\n')
s[len-1]='\0';
So at this point s points to a string up to 11 bytes long (including
the nul at the end) in a buffer 11 bytes long.
y=encrypt_strin g(s);
>int encrypt_string (s)
....
s[len++] = x;
s[len++] = rx;
s[len]= '\0';
Woops! You're adding things on to the end of s, and overflowing the
buffer.

You should be able to find mistakes like this yourself, using a
memory checking tool such as valgrind.

-- Richard
--
"Considerat ion shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Apr 25 '07 #3
bb****@gmail.co m wrote:
>
Why would this code cause undefined behavior?

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

#define TRUE 1
#define FALSE 0
#define MAX_PASSWORD 11
int loop;
unsigned char rx;

int _strlen(s)
unsigned char s[];
{
Because right here you have used a label reserved for the
implementation. Don't do that.

--
<http://www.cs.auckland .ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfoc us.com/columnists/423>
<http://www.aaxnet.com/editor/edit043.html>
cbfalconer at maineline.net

--
Posted via a free Usenet account from http://www.teranews.com

Apr 25 '07 #4
bb****@gmail.co m wrote:
Why would this code cause undefined behavior?
It was hard to resist rewriting this mess. Having resisted, I still
refuse to quote it all, except to note that
if(*s=!NULL){
free(s);
s=NULL;
}
probably is not what you meant.
if (*s = !NULL) ?* use some whitespace, for pete's sake */
does not mean the same thing as what you probably meant,
if (*s)
Apr 25 '07 #5
On 25 Apr 2007 05:50:31 -0700, bb****@gmail.co m wrote:
>
if(*s=!NULL){
free(s);
s=NULL;
}
else
printf("Could not deallocate memory\n");
Should read
if (s != NULL)
{
free(s);
s = NULL;
}
else
printf("Could not deallocate memory\n");
I guess.
G.

--

E-mail: info<at>simple-line<Punkt>de
Apr 25 '07 #6
Martin Ambuhl <ma*****@earthl ink.netwrote:
bb****@gmail.co m wrote:
if(*s=!NULL){
free(s);
s=NULL;
}
you probably meant,
if (*s)
I wouldn't think so; I see no reason why a dynamically allocated
string shouldn't be freed simply because its length is 0.

--
C. Benson Manica | I *should* know what I'm talking about - if I
cbmanica(at)gma il.com | don't, I need to know. Flames welcome.
Apr 25 '07 #7
Christopher Benson-Manica wrote:
Martin Ambuhl <ma*****@earthl ink.netwrote:
>bb****@gmail.co m wrote:
>> if(*s=!NULL){
free(s);
s=NULL;
}
>you probably meant,
if (*s)

I wouldn't think so; I see no reason why a dynamically allocated
string shouldn't be freed simply because its length is 0.
You're right. But guessing what the OP meant by his assignment
statement is up in the air. Any guess is likely to be wrong.

Apr 26 '07 #8
On Thu, 26 Apr 2007 00:29:11 -0400, Martin Ambuhl
<ma*****@earthl ink.netwrote:
>>>>
if(*s=!NULL){
free(s);
s=NULL;
}
>>you probably meant,
if (*s)

I wouldn't think so; I see no reason why a dynamically allocated
string shouldn't be freed simply because its length is 0.

You're right. But guessing what the OP meant by his assignment
statement is up in the air. Any guess is likely to be wrong.
Not so!

It should read
if (s != NULL)
{
free(s);
s = NULL;
}
else
printf("Could not deallocate memory\n");
I guess. (Such a construction -without the else-path- does make sense
_if_ it is possible that the allocated memory might have been freed
already at an earlier time. I once used such a construction, IIRC.)
G.

--

E-mail: info<at>simple-line<Punkt>de
Apr 26 '07 #9

"Gregor H." <nomail@invalid schrieb im Newsbeitrag
news:us******** *************** *********@4ax.c om...
On Thu, 26 Apr 2007 00:29:11 -0400, Martin Ambuhl
<ma*****@earthl ink.netwrote:
>>>>>
if(*s=!NULL){
free(s);
s=NULL;
}

you probably meant,
if (*s)

I wouldn't think so; I see no reason why a dynamically allocated
string shouldn't be freed simply because its length is 0.

You're right. But guessing what the OP meant by his assignment
statement is up in the air. Any guess is likely to be wrong.
Not so!

It should read
if (s != NULL)
{
free(s);
s = NULL;
}
else
printf("Could not deallocate memory\n");
I guess. (Such a construction -without the else-path- does make sense
_if_ it is possible that the allocated memory might have been freed
already at an earlier time. I once used such a construction, IIRC.)
You can feed free() with anything that got returned by malloc(), calloc() or
realloc() which in turn can return NULL, so you can safely call free(NULL)
unconditionally and safe that exta code.

free(s),s = NULL;

The mesages "Could not deallocate memory" is a) not neccessary (as you
haven't got any memory to free in the first place) and b) if at all should
go to stderr, shouldn't it?

Bye, Jojo
Apr 26 '07 #10

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

Similar topics

48
3099
by: marbac | last post by:
Hi, i heard a lot about "undefined behaviour" in this and other newsgroups dealing with c/c++. Is there a list where all cases with undefined behaviour in C++ are listed? regards marbac
19
2588
by: E. Robert Tisdale | last post by:
In the context of the comp.lang.c newsgroup, the term "undefined behavior" actually refers to behavior not defined by the ANSI/ISO C 9 standard. Specifically, it is *not* true that "anything can happen" if your C code invokes "undefined behavior". Behavior not defined by the ANSI/ISO C 9 standard may be defined by some other standard (i.e. POSIX) or it may be defined by your compiler, your operating system or your machine architecture.
66
3076
by: Mantorok Redgormor | last post by:
#include <stdio.h> struct foo { int example; struct bar *ptr; }; int main(void) { struct foo baz; baz.ptr = NULL; /* Undefined behavior? */ return 0;
25
3104
by: Nitin Bhardwaj | last post by:
Well, i'm a relatively new into C( strictly speaking : well i'm a student and have been doing & studying C programming for the last 4 years).....and also a regular reader of "comp.lang.c" I don't have a copy of ANSI C89 standard,therefore i had to post this question: What is the difference between "unspecified" behaviour & "undefined" behaviour of some C Code ??
30
22762
by: jimjim | last post by:
Hello, #include <stdio.h> int main(int argc, char *argv) { int x = 1; printf("%d %d %d\n", ++x, x, x++); return 0; }
33
2343
by: dragoncoder | last post by:
Hi all, Does the following code invoke undefined behaviour ? $ cat a1.cc #include <iostream> #include <limits> int main() { int a = INT_MAX/2;
14
2578
by: avsharath | last post by:
In "Bjarne Stroustrup's C++ Style and Technique FAQ" at: http://www.research.att.com/~bs/bs_faq2.html#evaluation-order for the statement: f(v,i++); he says that "the result is undefined because the order of evaluation of function arguments are undefined". But AFAIK, the order of evaluation of function arguments is unspecified
12
3070
by: Rajesh S R | last post by:
Can anyone tell me what is the difference between undefined behavior and unspecified behavior? Though I've read what is given about them, in ISO standards, I'm still not able to get the difference. For example: Consider the following code: a = i; We say that the above expression statement produces undefined
22
2029
by: blargg | last post by:
Does ~0 yield undefined behavior? C++03 section 5 paragraph 5 seems to suggest so: The description of unary ~ (C++03 section 5.3.1 paragraph 8): But perhaps "one's complement" means the value that type would have with all bits inverted, rather than the mathematical result of inverting all bits in the binary representation. For example, on a machine with 32-bit
33
2848
by: coolguyaroundyou | last post by:
Will the following statement invoke undefined behavior : a^=b,b^=a,a^=b ; given that a and b are of int-type ?? Be cautious, I have not written a^=b^=a^=b ; which, of course, is undefined. I am having some confusion with the former statement! Also, state the reason for the statement being undefined!
0
9546
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
10268
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
10247
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
10031
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6809
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
5467
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...
0
5593
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3762
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2941
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.