473,322 Members | 1,781 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

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 2004
In article <11**********************@e3g2000cwe.googlegroups. com>,
<cr*******@gmail.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_Keith) 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.announce.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
Thanks everyone! I eventually got this segment of my program to work..
although not as concisely as I would've hoped. If I get the rest of
this done early then I'll try a second stab at it.

Sep 23 '06 #11
Kenny McCormack said:
In article <11**********************@e3g2000cwe.googlegroups. com>,
<cr*******@gmail.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.
If you must play your silly little games, try to play them in a way that
doesn't cost people real money.

To the OP: the code is flawed, as you rightly guessed. There is no reason to
think that any RAM chips are defective. McCormack is simply being
McCormack.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Sep 23 '06 #12

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

Similar topics

5
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...
20
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...
6
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...
6
by: archilleswaterland | last post by:
structures typedef struct{ char name; int age; float balance; }account; account xyx; accout *ptr;
13
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>...
10
by: spacebebop | last post by:
#include <cstring> #include <iostream> using namespace std; class X { public: X(); X( char * ); ~X();
6
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 :...
16
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
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...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.