473,839 Members | 1,674 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

why this crash?

Hi,
It could be a very simple problem, but i can not see it...

Here is the code:

char* lower(char* str){
char* p = str;
while ( *str ) {
*str = tolower(*str); <=====crash!
str++;
}
return p;
}

DO you see why?

Jul 3 '07
16 1729
On Jul 3, 9:18 pm, "Army1987" <please....@for .itwrote:
>
Whitespace isn't significant in C.
It is significant in some places; this isn't valid:

#include<stdio. h>intmain(intar gc,char**argv){ return0;}
Jul 4 '07 #11
On Jul 3, 8:34 am, "Default User" <defaultuse...@ yahoo.comwrote:
linq...@hotmail .com wrote:
Hi,
It could be a very simple problem, but i can not see it...
Here is the code:
char* lower(char* str){
char* p = str;
while ( *str ) {
*str = tolower(*str); <=====crash!
str++;
}
return p;
}
DO you see why?

No. You only showed us part of the code. Post a complete, minimal
program that demonstrates the problem.

I'll bet you passed it a string literal.

Brian- Hide quoted text -

- Show quoted text -
Hi,
Why passing string literal crashes the program?
I've completed and made some tryings on his code.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* lower(char* str)
{
char* p = str;
while ( *str )
{
*str = tolower(*str); //<=====crash!
str++;
}
return p;
}
int main()
{
char *dd = (char *)malloc(sizeof (char)*2);
strcpy(dd,"DD") ;
puts(lower(dd)) ; //crashes, if changed with puts(lower("DD" ));
return 0;
}

Above code works , but if i call the lower func. with string literal
as an argument it crashes.
After crash i changed the declaration of func. lower as char*
lower(const char* str) but i got the compile error "assignment of read-
only location" at line labeled as //<=====crash!

What can be done on this fun. to work with string literals rather than
passing them to pointers ?

Thanks..

Jul 5 '07 #12
tguclu wrote:
On Jul 3, 8:34 am, "Default User" <defaultuse...@ yahoo.comwrote:
>linq...@hotmai l.com wrote:
Hi,
It could be a very simple problem, but i can not see it...
Here is the code:
char* lower(char* str){
char* p = str;
while ( *str ) {
*str = tolower(*str); <=====crash!
str++;
}
return p;
}
DO you see why?

No. You only showed us part of the code. Post a complete, minimal
program that demonstrates the problem.

I'll bet you passed it a string literal.
Why passing string literal crashes the program?
You're not allowed to update a string literal. If you try, the implementation
can do /anything it likes/. In this case, it was helpful, and blew your
program up.

(fx:snip)
char* lower(char* str)
int main()
{
char *dd = (char *)malloc(sizeof (char)*2);
strcpy(dd,"DD") ;
Oops. You've tried to copy three characters ('D', 'D', /and/ '\0')
into space big enough for only two. All Bets Are Now Off.
puts(lower(dd)) ; //crashes, if changed with puts(lower("DD" ));
After crash i changed the declaration of func. lower as char*
lower(const char* str) but i got the compile error "assignment of read-
only location" at line labeled as //<=====crash!
Well, of course.
What can be done on this fun. to work with string literals rather than
passing them to pointers ?
Nothing. You're not allowed to update string literals.

--
Hewlett-Packard Limited Cain Road, Bracknell, registered no:
registered office: Berks RG12 1HN 690597 England

Jul 5 '07 #13
tguclu wrote:
On Jul 3, 8:34 am, "Default User" <defaultuse...@ yahoo.comwrote:
linq...@hotmail .com wrote:
Hi,
It could be a very simple problem, but i can not see it...
Here is the code:
char* lower(char* str){
char* p = str;
while ( *str ) {
*str = tolower(*str); <=====crash!
str++;
}
return p;
}
I'll bet you passed it a string literal.
Why passing string literal crashes the program?
Basically the question answered here:

<http://c-faq.com/charstring/strlitinit.html >


Brian
Jul 5 '07 #14
tguclu wrote:
>
.... snip ...
>
int main()
{
char *dd = (char *)malloc(sizeof (char)*2);
strcpy(dd,"DD") ;
puts(lower(dd)) ; //crashes, if changed with puts(lower("DD" ));
return 0;
}

Above code works , but if i call the lower func. with string
literal as an argument it crashes.
Because string literals are not modifiable. Neither are they
marked as const, due to historical reasons. You can mark them as
const if you like. They may be stored in read-only memory, shared
with other declarations, etc.

--
<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 dot net

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

Jul 5 '07 #15
tguclu <tu**********@g mail.comwrites:
[...]
Why passing string literal crashes the program?
I've completed and made some tryings on his code.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* lower(char* str)
{
char* p = str;
while ( *str )
{
*str = tolower(*str); //<=====crash!
str++;
}
return p;
}
A stylistic note: you copy the original value of the parameter 'str'
to 'p', then modify 'str' in your loop. There's nothing wrong with
that, but I'd probably do it the other way around: maintain 'str' with
its original value, and modify the copy. It's not a big deal, I just
find it a bit clearer that way.
int main()
That's ok, but it's better to be more explicit:

int main(void)
{
char *dd = (char *)malloc(sizeof (char)*2);
Don't cast the result of malloc. See questions 7.7, 7.7b, and 7.7c in
the FAQ, <http://www.c-faq.com/>. In fact, *most* casts are
unnecessary.

sizeof(char) is 1 by definition. If you know you're always going to
be allocating characters, you can write the above as:

char *dd = malloc(2);

If there's some possibility that you might change dd to some other
pointer type in the future, the recommended idiom is:

char *dd = malloc(2 * sizeof *dd);

(By applying sizeof to *dd, you automatically get the right type even
if you change the declaration).

malloc can fail; it indicates failure by returning a null pointer
value. Always check for this. (It's probably ok to leave out the
check in a small sample program like this one, but in that case add a
comment saying that you've left it out.)
strcpy(dd,"DD") ;
As somebody else pointed out, this copies 3 bytes ('D', 'D', '\0')
into an array of 2 elements (assuming malloc succeeded).

If I wanted to make sure the code is flexible in the face of future
changes, I might do this:

#define THE_STRING "DD"
char *dd = malloc(sizeof THE_STRING);
/* check whether malloc failed */
strcpy(dd, THE_STRING);

or perhaps:

#define THE_STRING "DD"
char *dd = malloc(strlen(T HE_STRING) + 1);
/* check whether malloc failed */
strcpy(dd, THE_STRING);

I'm not suggesting that this kind of thing is necessary for a small
sample program like this one, but it's something to keep in mind for
future programs.
puts(lower(dd)) ; //crashes, if changed with puts(lower("DD" ));
return 0;
}
[...]

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jul 5 '07 #16
On Jul 2, 11:34 pm, "Default User" <defaultuse...@ yahoo.comwrote:
linq...@hotmail .com wrote:
Hi,
It could be a very simple problem, but i can not see it...
Here is the code:
char* lower(char* str){
char* p = str;
while ( *str ) {
*str = tolower(*str); <=====crash!
str++;
}
return p;
}
DO you see why?

No. You only showed us part of the code. Post a complete, minimal
program that demonstrates the problem.

I'll bet you passed it a string literal.

Brian
Your bet wins.

Jul 6 '07 #17

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

Similar topics

48
8527
by: Joseph | last post by:
Hi I'm writing a commercial program which must be reliable. It has to do some basic reading and writing to and from files on the hard disk, and also to a floppy. I have foreseen a potential problem. The program may crash unexpectedly while writing to the file. If so, my program should detect this during startup, and then (during startup) probably delete the data added to the file and redo the writing operation.
8
3221
by: Eric Brunel | last post by:
Hi all, I was creating a Tkinter widget in the style of the reversed tabs below Excel worksheets and I stepped in a serious problem: the code I made makes python crash with a seg fault, bus error or X11 BadGC error on both Solaris (2.6 and 2.7) and Linux (Mandrake 8.0); it doesn't crash on Windows. I tried to simplify the script, but I couldn't reproduce the crash with a simpler code. So the code below is somewhat long; sorry for that. ...
0
2277
by: roni | last post by:
hi. i have application written in vb.net + managed c++ dll that call also to unmanaged c++ function. the application crash. i open the dump file of the crash with WinDbg and that's is the call stack (using the sos.dll) : =====================================
10
9551
by: xixi | last post by:
i have db2 udb v8.1 on windows 64 bit 2003 server, after db2 server start , i found this in the db2diag.log, is this error? 2004-05-05-15.28.30.780000 Instance:DB2 Node:000 PID:1692(db2syscs.exe) TID:2860 Appid:AC10040A.GD5F.00FC56D8BEC5 base sys utilities sqledint Probe:30 Crash Recovery is needed. 2004-05-05-15.28.31.890000 Instance:DB2 Node:000
8
6466
by: Adam Louis | last post by:
I would like help resolving this problem. I'm a novice who's been hired to query a hospital database and extract useful information, available to me only in a dynamically generated, downloadable .mdb. The query below query runs correctly and without error, but any attempt to save it causes Access to crash without a message, leaving the .ldb file. Opening the DB reveals it saved a blank "query1". I've upgraded to Jet SP 8, and I'm running...
14
5279
by: JK Peck | last post by:
I have a fairly large Access application that ran correctly in Access 2000. After upgrading to Access 2003 (and recompiling and updating references), it reliably crashes at a certain point. If I step through the VBA code, the crash does not occur. What is different about stepping through code instead of just running it? Any idea how to find the cause? I know about where it happens, but since it is Access itself crashing, finding a...
34
4482
by: NewToCPP | last post by:
Hi, Why does a C/C++ programs crash? When there is access to a null pointer or some thing like that programs crash, but why do they crash? Thanks.
12
5604
by: benjamin.krulewitch | last post by:
I'm debugging an issue with a C program that causes the computer to crash, and I'm attempting to log information immediately before the crash occurs. I us my BKprintLog function (see below) to write information into a log file. The problem is, i'm not confident that information i write to the log gets saved onto the hard drive before the crash occurs. My understanding of hard drives and OS are that because hard drives are so slow,...
110
10658
by: alf | last post by:
Hi, is it possible that due to OS crash or mysql itself crash or some e.g. SCSI failure to lose all the data stored in the table (let's say million of 1KB rows). In other words what is the worst case scenario for MyISAM backend? Also is it possible to not to lose data but get them corrupted?
11
3061
by: =?Utf-8?B?R2VyaGFyZA==?= | last post by:
I have run into a situation that if a page/tab that uses the Ajax toolkit (using .net version 3.5) is closed before the Ajax enable controls complete loading, then IE locks up. Does it in both IE7 and IE8. There is no issue when the controls are allowed to complete loading. Can you please tell me the best practice that handles this? Thanks.
0
9856
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
9698
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
10910
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
10654
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
9426
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7833
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7021
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
5867
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4493
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

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.