473,947 Members | 1,737 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

bus errors accessing a char * by index?!

i can't seem to figure out why this code refuses to work:

char *s = "hello";
printf("%s", s[0]);

i keep getting bus errors when i run this. whyyyyyy?

i also get the same type of errors when trying to do strncpy and such.

please help.

Sep 22 '06 #1
11 2054
In article <11************ **********@e3g2 000cwe.googlegr oups.com>,
<cr*******@gmai l.comwrote:
>i can't seem to figure out why this code refuses to work:

char *s = "hello";
printf("%s", s[0]);

i keep getting bus errors when i run this. whyyyyyy?

i also get the same type of errors when trying to do strncpy and such.

please help.
Sounds like a defective RAM chip. You need to buy a new computer.

Sep 22 '06 #2
cr*******@gmail .com wrote:
i can't seem to figure out why this code refuses to work:

char *s = "hello";
printf("%s", s[0]);
You are using the %s format specifier, which is used to print a C
string, i.e. a pointer to a null terminated sequence of chars.

s[0], in your example, is a char.

See the problem?

[hint: what does the %c format specifier do?]
>
i keep getting bus errors when i run this. whyyyyyy?

i also get the same type of errors when trying to do strncpy and such.

please help.
HTH,
--ag

--
Artie Gold -- Austin, Texas
http://goldsays.blogspot.com
"You can't KISS* unless you MISS**"
[*-Keep it simple, stupid. **-Make it simple, stupid.]
Sep 22 '06 #3
char *s = "hello";
printf("%s", s[0]);

i keep getting bus errors when i run this. whyyyyyy?
You probably want to do either:
printf("%s", s); /* print the whole string */
or
printf("%s", &s[0]); /* print the whole string; another way to say
the same thing */
or
printf("%c", s[0]); /* print just the first character. */

Something along the following lines is happening (although this is
implementation defined, so it may not be exactly this):

Let's say s is stored at memory location 0x123456
My version 1 says 'print the string starting at memory location
0x123456'
My version 2 says 'print the string starting at the memory location
that is the address of the first character of s' (which is, in turn,
0x123456, which is fine).
My version 3 says 'print the character s[0]' which is 'h' which is
ascii 0x68.
Now here's the kicker:
Your version says 'print the string starting at memory location
0x68.' But who knows what is at 0x68? Probably garbage. Or worse.

Michael

Sep 22 '06 #4
ahh.. okay i see. now why can't i write to:

char *s = "hello";
s[3]='\0'; <-causes the error
printf("%s", s);

?

basically, the bigger picture what i'm trying to is extract words from
a string with / as its delimiter , such as

char * s = "dirA/dirB";

by finding the index of the / , set s[4]='\0', so now i have two
strings: s is "dirA" and (s+4) is "dirB"

Sep 22 '06 #5
cr*******@gmail .com writes:
ahh.. okay i see.
You see what? Please provide context when posting a followup.

Suggested links:

http://cfaj.freeshell.org/google/
http://www.caliburn.nl/topposting.html
http://clc-wiki.net/wiki/Introduction_to_comp.lang.c

It would also be helpful if you would use standard capitalization; by
making it easier it is for us to read what you write, you can help us
to help you.
now why can't i write to:

char *s = "hello";
s[3]='\0'; <-causes the error
printf("%s", s);
?
What exactly do you mean by "causes the error"? The problem in this
case happens to be fairly obvious, but in general it's very important
to tell us *what* went wrong. You might also want to read
<http://www.catb.org/~esr/faqs/smart-questions.html> .

The problem is that you're trying to modify a string literal. A
string literal such as "hello" specifies a statically allocated array
of characters. Any attempt to modify this array, as you've done
above, invokes undefined behavior, which means it may or may not work,
and the compiler isn't obligated to tell you that you've made a
mistake. Don't do that.

If you want a string you can modify, you can declare it like this:

char s[] = "hello";

Here you declare an array (which you can modify), and the string
literal specifies how the array is initialized. This is in contrast
to your original declaration, in which the *pointer* is initialized to
point to the (possibly unmodifiable) array associated with the string
literal itself.
basically, the bigger picture what i'm trying to is extract words from
a string with / as its delimiter , such as

char * s = "dirA/dirB";

by finding the index of the / , set s[4]='\0', so now i have two
strings: s is "dirA" and (s+4) is "dirB"
You might want to look at the standard strtok() function. It has some
serious problems (it modifies the string you're splitting, it can't be
used on more than one string at a time, and its treatment of
consecutive delimiters is questionable), but it may be just what
you're looking for.

--
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.
Sep 23 '06 #6
On 22 Sep 2006 17:09:00 -0700, in comp.lang.c , cr*******@gmail .com
wrote:
>ahh.. okay i see. now why can't i write to:

char *s = "hello";
s[3]='\0'; <-causes the error
printf("%s", s);
This is a FAQ - 16.8.
>basically, the bigger picture what i'm trying to is extract words from
a string with / as its delimiter , such as

char * s = "dirA/dirB";
once you've figured out why you can't modify this, you will be able to
solve your problem using an array of chars.
>by finding the index of the / , set s[4]='\0', so now i have two
strings: s is "dirA" and (s+4) is "dirB"
--
Mark McIntyre

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Sep 23 '06 #7
cr*******@gmail .com wrote:
>
.... snip ...
>
basically, the bigger picture what i'm trying to is extract words
from a string with / as its delimiter , such as

char * s = "dirA/dirB";

by finding the index of the / , set s[4]='\0', so now i have two
strings: s is "dirA" and (s+4) is "dirB"
Just look up strtok(). All done.

--
Some informative links:
news:news.annou nce.newusers
http://www.geocities.com/nnqweb/
http://www.catb.org/~esr/faqs/smart-questions.html
http://www.caliburn.nl/topposting.html
http://www.netmeister.org/news/learn2quote.html

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

Sep 23 '06 #8
CBFalconer wrote:
cr*******@gmail .com wrote:
... snip ...
>basically, the bigger picture what i'm trying to is extract words
from a string with / as its delimiter , such as

char * s = "dirA/dirB";

by finding the index of the / , set s[4]='\0', so now i have two
strings: s is "dirA" and (s+4) is "dirB"

Just look up strtok(). All done.
strtok() wouldn't help in this case. The same issue would still be there
(bus error in OP's case, segmentation violation in my experience). In
short you cannot modify a string literal and it's important for the OP
to know this distinction.

Below is the strtok() route and below that is the method you previously
mentioned. Either one will work. The second one is probably more complex
than needed, but it gets the job done.

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

int main(void)
{
char s[] = "dirA/dirB";
char *p = NULL;
int i = 0;

p = strtok(s, "/");

if (p == NULL)
{
printf("Whoops! strtok() returned NULL\n";
return(0);
}

while(p != NULL)
{
printf("element %d: \"%s\"\n", i, p);
p = strtok(NULL, "/");
}

return(0);
}

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

int main(void)
{
char s[] = "dirA/dirB";
int i = 0;
int j = 0;
int totElem = 1;
int len = strlen(s);
char *p = NULL;

for (i = 0; i < len; i++)
{
if (s[i] == '/')
{
s[i] = '\0';
totElem++;
}
}

p = s;
for (i = 0; i < totElem; i++)
{
printf("element %d: \"%s\"\n", i, p);

for (j = 0; p[j] != '\0'; j++) ;
p += j + 1;
}

return(0);
}
Sep 23 '06 #9
Joe Estock wrote:
CBFalconer wrote:
>cr*******@gmail .com wrote:
... snip ...
>>basically, the bigger picture what i'm trying to is extract words
from a string with / as its delimiter , such as

char * s = "dirA/dirB";

by finding the index of the / , set s[4]='\0', so now i have two
strings: s is "dirA" and (s+4) is "dirB"

Just look up strtok(). All done.

strtok() wouldn't help in this case. The same issue would still be there
(bus error in OP's case, segmentation violation in my experience). In
short you cannot modify a string literal and it's important for the OP
to know this distinction.

Below is the strtok() route and below that is the method you previously
mentioned. Either one will work. The second one is probably more complex
than needed, but it gets the job done.

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

int main(void)
{
char s[] = "dirA/dirB";
char *p = NULL;
int i = 0;

p = strtok(s, "/");

if (p == NULL)
{
printf("Whoops! strtok() returned NULL\n";
return(0);
}

while(p != NULL)
{
printf("element %d: \"%s\"\n", i, p);
p = strtok(NULL, "/");
i++;

/* Might help to increment the counter variable. */
}

return(0);
}

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

int main(void)
{
char s[] = "dirA/dirB";
int i = 0;
int j = 0;
int totElem = 1;
int len = strlen(s);
char *p = NULL;

for (i = 0; i < len; i++)
{
if (s[i] == '/')
{
s[i] = '\0';
totElem++;
}
}

p = s;
for (i = 0; i < totElem; i++)
{
printf("element %d: \"%s\"\n", i, p);

for (j = 0; p[j] != '\0'; j++) ;
p += j + 1;
}

return(0);
}
Sep 23 '06 #10

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

Similar topics

5
4452
by: Claudio Grondi | last post by:
Background information: --------------------------------- in order to monitor mainboard sensory data as fan speeds, temperatures, applications like SpeedFan http://www.almico.com/speedfan.php or MBM http://mbm.livewiredev.com/ can be used. Both of the mentioned apps expose data got from the hardware in a shared memory area.
20
2774
by: Nick Burrett | last post by:
Hi, I'm having a little difficultly with a database that I'm upgrading from Postgres 7.2.1 to 7.3.4. On the 7.2.1 server I did: $ pg_dump fiveminute >fiveminute.db $ pg_dump bandwidth >bandwidth.db
6
1961
by: Erica | last post by:
Hi, I am currently working on a Pascal-to-C translation, and I am getting an error that I can't seem to debug. I have a globals.h file, and here is a snippet from it: -- typedef char ShortString;
6
2094
by: archilleswaterland | last post by:
structures typedef struct{ char name; int age; float balance; }account; account xyx; accout *ptr;
13
1452
by: GeekBoy | last post by:
Seems I am having trouble understanding make a relation of accessing the structs in functions; Thanks in advance, since 10^10 messages an hour go through here. #include<iostream> #include<fstream> #include<string>
10
1439
by: spacebebop | last post by:
#include <cstring> #include <iostream> using namespace std; class X { public: X(); X( char * ); ~X();
6
2128
by: andrey.vul | last post by:
The error is LNK2001: unresolved external symbol "protected: static bool solver<typename, typename, int, int, int, int, int>::solution" (<vc++ mangled name>) Code (sudoku.cpp): // Sudoku.cpp : Defines the entry point for the console application. // #include <iostream> #include <vector> #include <stdexcept> #include <cstdlib>
16
6818
by: s0suk3 | last post by:
This code #include <stdio.h> int main(void) { int hello = {'h', 'e', 'l', 'l', 'o'}; char *p = (void *) hello; for (size_t i = 0; i < sizeof(hello); ++i) {
2
1981
by: TamaThps | last post by:
Hi, I'm using visual studio 2008 and normally when I get an error it shows what line it is on and which file etc. The error I'm getting I don't know how to solve or even what the problem is. This is the whole output when I try to run the program. "1>------ Build started: Project: corysid, Configuration: Debug Win32 ------ 1>Compiling... 1>implementation.cpp 1>Linking... 1>actualmain.obj : error LNK2019: unresolved external symbol "public:...
0
10164
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
9985
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
11577
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
11173
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
11352
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
6118
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
4948
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
4540
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3544
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.