473,569 Members | 2,716 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

strlen() and segfault?

Wrote simple program to setup a char array of pointers and print each
one. It runs with the expected output however it then causes a
segmentation fault. Could someone take a lot at the code? My debugging
is below as well. Should I have malloc'd memory for each of the
strings? The examples I've studies so far from K&R and K&A didn't
indicate that was needed. I haven't learned malloc yet anyways :-)

Zach

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

#define NUMSTRINGS 3

int main (void)
{

char *strings[NUMSTRINGS] = {
"Testing 1",
"Testing 2",
"Testing 3"
};

int i;

for (i=0; i <= NUMSTRINGS; i++) {
printf("%s", strings[i]);
printf("\n");
}

return(EXIT_SUC CESS);
}

zu22@netrek:~/src/testing$ gcc -g char-array2.c
zu22@netrek:~/src/testing$ gdb ./a.out
GNU gdb 6.4.90-debian
Copyright (C) 2006 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and
you are
welcome to change it and/or distribute copies of it under certain
conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for
details.
This GDB was configured as "i486-linux-gnu"...Using host libthread_db
library "/lib/libthread_db.so .1".

(gdb) run
Starting program: /home/zu22/src/testing/a.out
Testing 1
Testing 2
Testing 3

Program received signal SIGSEGV, Segmentation fault.
0x400959db in strlen () from /lib/libc.so.6
(gdb) bt
#0 0x400959db in strlen () from /lib/libc.so.6
#1 0x4006b327 in vfprintf () from /lib/libc.so.6
#2 0x40070cd3 in printf () from /lib/libc.so.6
#3 0x080483da in main () at char-array2.c:19
(gdb) quit
The program is running. Exit anyway? (y or n) y

Feb 14 '07 #1
5 7529
Zach wrote:
Wrote simple program to setup a char array of pointers and print each
one. It runs with the expected output however it then causes a
segmentation fault. Could someone take a lot at the code? My debugging
is below as well. Should I have malloc'd memory for each of the
strings? The examples I've studies so far from K&R and K&A didn't
indicate that was needed. I haven't learned malloc yet anyways :-)

Zach

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

#define NUMSTRINGS 3

int main (void)
{

char *strings[NUMSTRINGS] = {
"Testing 1",
"Testing 2",
"Testing 3"
};

int i;

for (i=0; i <= NUMSTRINGS; i++) {
Should be < NUMSTRINGS. The array is indexed from 0 to NUMSTRINGS-1.

--
Ian Collins.
Feb 14 '07 #2
On Feb 13, 4:59 pm, "Zach" <net...@gmail.c omwrote:
Wrote simple program to setup a char array of pointers and print each
one. It runs with the expected output however it then causes a
segmentation fault. Could someone take a lot at the code? My debugging
is below as well. Should I have malloc'd memory for each of the
strings? The examples I've studies so far from K&R and K&A didn't
indicate that was needed. I haven't learned malloc yet anyways :-)

Zach

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

#define NUMSTRINGS 3

int main (void)
{

char *strings[NUMSTRINGS] = {
"Testing 1",
"Testing 2",
"Testing 3"
};

int i;

for (i=0; i <= NUMSTRINGS; i++) {
printf("%s", strings[i]);
printf("\n");
}

return(EXIT_SUC CESS);

}
(snipped)

As others have told you: access is
outside the bounds of array string
when i == NUMSTRINGS.
One might consider using an initializer
list to determine the size of the array.
In this way one can add to or take
away from the initializer list without
having to make other updates to the code.
E.g.,

int main (void)
{
char *string [] = {
"Testing 1",
"Testing 2",
"Testing 3",
};

size_t i;

for (i = 0; i < sizeof string / sizeof string[0]; ++i)
printf("%s\n", string[i]);

return EXIT_SUCCESS;

}

--
Hope this helps,
Steven

Feb 14 '07 #3
Thanks for the responses. I'll make sure I remember array indexes in C
run from
0 to (LENGTH - 1) and not 1 to LENGTH :-)

Zach

Feb 14 '07 #4
Zach <ne****@gmail.c omwrote:
Wrote simple program to setup a char array of pointers and print each
one.
Plus an extra one that doesn't exist...
char *strings[NUMSTRINGS] = {
"Testing 1",
"Testing 2",
"Testing 3"
};
for (i=0; i <= NUMSTRINGS; i++) {
printf("%s", strings[i]);
printf("\n");
}
What happens when i == NUMSTRINGS? strings is indexed from 0 to
NUMSTRINGS-1, so you meant

for (i=0; i < NUMSTRINGS; i++) {

You either learned something or are kicking yourself; hopefully the
former (from someone who's done his share of the latter).

--
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.
Feb 14 '07 #5
On Feb 13, 11:44 pm, Christopher Benson-Manica
<a...@otaku.fre eshell.orgwrote :
>
You either learned something or are kicking yourself; hopefully the
former (from someone who's done his share of the latter).
Yes I definitely learned my lesson. :) Thanks to all who responded.

Zach

Feb 14 '07 #6

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

Similar topics

12
3143
by: Nathaniel Echols | last post by:
I've written a function in C to perform protein sequence alignment. This works fine in a standalone C program. I've added the necessary packaging to use it in Python; it returns three strings and an integer. However, as soon as the function is complete, I get a segfault and the interpreter dies. If I run Python interactively, just...
6
1976
by: Stefan Behnel | last post by:
Hi! In Python 2.4b3, the deque is causing a segfault on two different machines I tested on. With deque, my program runs fine for a while (at least some tens of seconds up to minutes) and then suddenly segfaults. I'm sorry I can't tell exactly when, but I'm running an application that uses a few hundred deques where elements are...
0
1813
by: dale | last post by:
Python newbie disclaimer on I am running an app with Tkinter screen in one thread and command-line input in another thread using raw_input(). First question - is this legal, should it run without issue? If not can you point me to a description of why. While updating objects on the screen I get a segfault after an indeterminate number...
10
1934
by: name | last post by:
When I started testing the algorithms for my wrap program, I threw together this snippet of code, which works quite well. Except that it (predictably) segfaults at the end when it tries to go beyond the file. At some point, I tried to mend that behavior using feof() but without success. The functionality is not harmed, but this has started...
3
2296
by: kj | last post by:
I am trying to diagnose a bug in my code, but I can't understand what's going on. I've narrowed things down to this: I have a function, say foo, whose signature looks something like: int foo( int w, int x, int y, int z, my_struct **results ) During its execution, foo initializes *results using calloc: ( *results ) = calloc( w+1,...
10
533
by: danielesalatti | last post by:
Hello!! I'm studying c++ and I'm trying to get a little piece of code working, but I'm getting a segfault with strlen here: void tabhash::set (url *U) { uint hash = U->hashCode(); char* url = U->giveUrl(); char* chash = (char*)hash; char* Insert1="INSERT INTO sep_hashtable VALUES (";
44
25000
by: sam_cit | last post by:
Hi Everyone, I tried the following program unit in Microsoft Visual c++ 6.0 and the program caused unexpected behavior, #include <stdio.h> #include <string.h> int main() {
53
717
by: ¬a\\/b | last post by:
strlen is wrong because can not report if there is some error e.g. char *a; and "a" point to an array of size=size_t max that has no 0 in it
14
4945
by: Donn Ingle | last post by:
Yo, An app of mine relies on PIL. When PIL hits a certain problem font (for unknown reasons as of now) it tends to segfault and no amount of try/except will keep my wxPython app alive. My first thought is to start the app from a bash script that will check the return value of my wxPython app and could then launch a new app to help the user...
0
7694
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...
0
8118
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...
0
7964
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...
0
6278
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...
1
5504
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...
0
5217
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...
0
3636
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1208
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
936
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...

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.