473,714 Members | 2,527 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Strange problem on GCC - PLEASE HELP!!

I am compiling and running the following code snippet on a Linux box -
I am really
puzzled by the answers. Could someone please tell me what might be
wrong?

void test(){
int m = 0;
int n = 0;
int i = 0;
int j = 0;

double start = 0.0;
double end = 0.0;
double gap = 0.0;
struct timeval tp;

aes_context ctx;

unsigned char buf[16];

unsigned char key[32];

for(i = 0; i < 16; i++){ buf[i] = 'a'; }

for(j = 0; j < 32; j++){ key[j] = '9'; }

printf("%d, %d\n", strlen(buf), strlen(key));

/* Some more code omitted */
}

The print statements provide the answers 16, 48
Could someone please provide some hint as to what might be the problem?

Nov 14 '05 #1
5 1562
cp**********@ya hoo.com wrote:
I am compiling and running the following code snippet on a Linux box -
I am really
puzzled by the answers. Could someone please tell me what might be
wrong?

void test(){
int m = 0;
int n = 0;
int i = 0;
int j = 0;

double start = 0.0;
double end = 0.0;
double gap = 0.0;
struct timeval tp;

aes_context ctx;

unsigned char buf[16];

unsigned char key[32];

for(i = 0; i < 16; i++){ buf[i] = 'a'; }

for(j = 0; j < 32; j++){ key[j] = '9'; }

printf("%d, %d\n", strlen(buf), strlen(key));
1. strlen() returns values of the type size_t; size_t is an unsigned
integer type and not necessarily the same as unsigned int.
With C89, use
printf("%lu\n", (unsigned long)strlen(som estring));
with C99, you have a separate length modifier for size_t:
printf("%zu\n", strlen(somestri ng));
2. Valid C strings are _always_ terminated by a character with the
value 0, often written as '\0' and referred to as string terminator.
Your arrays of char do not contain C strings. In order to do so, one
array element in the range 0 .. sizeof buf -1 (or sizeof key -1,
respectively) needs to be zero.
Otherwise, strlen() keeps probably reading through the memory until
it encounters a byte of value 0. Why probably? Because the behaviour
is undefined. It is also possible that the program dies with a
segmentation fault or that your computer crashes.

/* Some more code omitted */
}

The print statements provide the answers 16, 48
Could someone please provide some hint as to what might be the problem?


In your case, it is possible that the first byte after the storage
reserved for buf is '\0', so you get sizeof buf. Moreover, it could
be that key is stored right before buf, so you have sizeof key plus
sizeof buf until '\0' is encountered. This is highly speculative.

To get you started:

#define SOMELEN (16)
.....
char mybuf[SOMELEN+1];
for (i=0; i<SOMELEN; i++)
mybuf[i] = '.';
mybuf[SOMELEN] = '\0';
printf("String length is %scorrect\n", strlen(mybuf)== SOMELEN
? "":"not ");

Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 14 '05 #2
unsigned char buf[16];

unsigned char key[32];


Try

unsigned char buf[16] = {};
unsigned char key[32] = {};

to initialize them to all \0s

so the strings will actually end (a string for use with the
standard libraries (calls such as strlen, printf, etc) ends at some \0)

as long as you keep some \0

and go from there

-Mysid

Nov 14 '05 #3
On 11 Feb 2005 14:58:53 -0800, cp**********@ya hoo.com wrote in
comp.lang.c:
I am compiling and running the following code snippet on a Linux box -
I am really
puzzled by the answers. Could someone please tell me what might be
wrong?

void test(){
int m = 0;
int n = 0;
int i = 0;
int j = 0;

double start = 0.0;
double end = 0.0;
double gap = 0.0;
struct timeval tp;

aes_context ctx;

unsigned char buf[16];

unsigned char key[32];

for(i = 0; i < 16; i++){ buf[i] = 'a'; }

for(j = 0; j < 32; j++){ key[j] = '9'; }

printf("%d, %d\n", strlen(buf), strlen(key));
Obviously you don't have a prototype for strlen() in scope, usually
done by including <string.h>, or you are operating your compiler in a
broken (non conforming) mode. Because the argument to strlen() must
be a pointer to char, and you are passing pointer to unsigned char.
No automatic conversion is possible, so each call to strlen() would be
a constraint violation.

Actually calling strlen() with a pointer to unsigned char produces
undefined behavior.

Even if you change buf and key to arrays of char, instead of unsigned
char, they are not strings, just arrays. Calling strlen() with a
pointer to char that is not a pointer to a string also produces
undefined behavior.
/* Some more code omitted */
}

The print statements provide the answers 16, 48
Could someone please provide some hint as to what might be the problem?


So...

1. Turn up the warning level on your compiler.

2. Invoke it in standard conforming mode.

3. Include <string.h> before calling strlen().

4. Do not pass pointers to unsigned char to strlen().

5. Do not pass pointers to character arrays that are not strings to
strlen().

Then your problem will go away.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #4
I would suggest to make some modifications in your code as bellow

unsigned char buf[17]; //array bound 17 to include '\0' string
termination character.
unsigned char key[33]; //Same justification as above.
for(i = 0; i < 16; i++){ buf[i] = 'a'; }
for(j = 0; j < 32; j++){ key[j] = '9'; }

buf[i] = '\0'; /*This is required as string terminates
with '\0' as you know*/
key[j] = '\0';

BTW just modifiying the code to unsigned char buf[17] = {}; will not
work because = {}; does not implicitely put '\0' at all positions of
array.

Nov 14 '05 #5
Mysidia wrote:
Try

unsigned char buf[16] = {};
unsigned char buf[16] = { 0 };
unsigned char key[32] = {};
unsigned char key[32] = { 0 };
to initialize them to all \0s

There is no such thing as an empty initializer.
Christian
Nov 14 '05 #6

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

Similar topics

2
2209
by: leegold2 | last post by:
How do I use rawurlencode()? A snippet would extremely appreciated. I read I should use it twice for plus signs(?) - I need help! Thanks. Very strange stuff happens when I use GET to pass a string like '+high +altitude'. Literally that's my (a legitimate) test string in a Mysql Boolean Fulltext search. Other non alplas are also causing strangeness. Not at first from my user search form, but during pagination of the results, as I GET the...
5
1259
by: brulsmurf | last post by:
Ok iam despered, in Main of this code the object 'two' is looking as should be when i print it, but the exact same code in procedure "duTest" makes the object filled up with additional strange values. I played with this code for hours but i cant find the problem. Plz help me #include "genetic.h" #include "neuron.h" #include "network.h"
3
4603
by: Bill C. | last post by:
Hi, I've got a simple console app that just reads an XML file into a DataSet then prints out a description of each table in the DataSet, including column names and row values for each column. I'm getting some strange results depending the input XML file I use. I was wondering if somebody could help me understand what is going on or point me to a good reference. The code for my program looks like this:
3
1716
by: Mitchell Thomas | last post by:
I hope someone out there can solve my mysterious problem. I have tried everything imaginable, even paid $35 to Microsoft to help me, but they were not able to figure out this problem: Here is the problem: I recently created a new database in Access 2002. I took data from an > access 97 database converted one of the tables to access 2002 and then > imported it into a new table in access 2002. but for some strange > reason, every once...
0
1108
by: unknown | last post by:
Hi, I am developing an online book store with shopping cart. My shopping cart is represented as a Xml server control and I am using an XSLT to render it at the client side. I am using an XmlDocument object as session variable to represent my shopping cart. Initially when the session starts, I am using the XmlDocument with root and no elements to show that no items have been added to the
1
1444
by: Martin Feuersteiner | last post by:
Dear Group I'm having a very weird problem. Any hints are greatly appreciated. I'm returning two values from a MS SQL Server 2000 stored procedure to my Webapplication and store them in sessions. Like This: prm4 = cmd1.CreateParameter With prm4
0
1381
by: David Pratt | last post by:
Hi. I am creating a couple of small methods to help me manage time from UTC as standard but I am getting strange results. If I start with a datetime of 2005-12-12 14:30:00 in timezone 'America/Halifax' and I want to turn this into a UTC representation. from datetime import datetime from pytz.reference import UTC import pytz
11
2593
by: Martin Joergensen | last post by:
Hi, I've encountered a really, *really*, REALLY strange error :-) I have a for-loop and after 8 runs I get strange results...... I mean: A really strange result.... I'm calculating temperatures. T = 20 degrees at all times.... The 2D T-array looks like this:
6
2268
by: Joseph Geretz | last post by:
Writing an Outlook AddIn with C#. For the user interface within Outlook I'm adding matching pairs of Toolbar buttons and Menu items. All of the buttons and menu items are wired up to send events to the same method (aka delegate?). I use the Tag property within this method to determine what user action is taking place. Very simple: When adding toolbar button: tbButton.Click += new...
14
3343
by: blumen | last post by:
Hi all, I'm a newbie in VB.Net Programming.. Hope that some of you can help me to solve this.. I'm working out to read,parse and save textfile into SQL Server. The textfile contains thousands of rows with about 50 coloums every row.. Everythings goes well until I found one textfile with some strange character...seems to be Japanese character(because it's a Japanese company who owns this textfile)
0
8796
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8704
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
9307
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...
1
9071
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
9009
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
5943
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
4462
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...
2
2514
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2105
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.