Wow, this is quite interesting! Actually, the while was not segfaulting because I had printf's in there just to make sure and they all printed fine. Now as far as the strtok() thing is concerned, that was the problem, as you said. This is interesting because I have, in the past, used strtok() this way and it has worked. So I don't know why this does not work now. In any case, my problem is solved.

Thanks Rob !
Nitin

On Mar 8, 2005, at 5:23 PM, Sisyphus wrote:

[EMAIL PROTECTED] wrote:
OK, I feel really stupid asking this since this is a *really* simple piece of code (this represents a piece of the bigger problem) but I keep segfaulting when I do the av_len() below. Any ideas?
Thanks !
Nitin
------------------------------
use Inline C => DATA =>;
use strict;
my $sentence = "My name is nitin madnani";
&print_words($sentence);
__DATA__
__C__
void print_words(SV* sentence) {
AV* mywords;
char *sent, *pch;
int i;
SV* myword;
SV** tmp;
sent = SvPV_nolen(sentence);
mywords = newAV();
pch = strtok(sent," ");
myword = newSVpvn(pch, strlen(pch));
SvPOK_on(myword);
av_push(mywords, myword);
while (pch) {
pch = strtok(NULL, " ");
myword = newSVpvn(pch, strlen(pch));
SvPOK_on(myword);
av_push(mywords, myword);
}
for(i=0;i<av_len(mywords);i++) {
tmp = av_fetch(mywords, i, 0);
printf("%s\n", SvPV_nolen(*tmp));
}
}
-------------------------------------------

This version works ok for me:

void print_words(SV* sentence) {
        AV* mywords;
        char *sent, *pch;
        int i;
        SV* myword;
        SV** tmp;

        sent = SvPV_nolen(sentence);
        mywords = newAV();

        pch = strtok(sent," ");

        while(pch != NULL) {
             myword = newSVpvn(pch, strlen(pch));
             SvPOK_on(myword);
             av_push(mywords, myword);
             pch = strtok(NULL, " ");
        }

        for(i=0;i<=av_len(mywords);i++) {
                tmp = av_fetch(mywords, i, 0);
                printf("%s\n", SvPV_nolen(*tmp));
        }
}


Seemed to me that the segfault I was getting with your original code occurred at 'while(pch)'.


Not exactly sure of the reason - but note that the first time strtok() is called I haven't pushed pch onto the array. It's only when you start iterating through the loop that you want to push pch onto the array.

Also av_len() returns the highest array index (not the length) of the array, so you probably wanted 'i<=av_len(mywords)' instead of 'i<av_len(mywords)'.

Not sure that it's necessary to do the SvPOK_on() ... and haven't checked. Instinctively, I feel it would not be necessary.

Cheers,
Rob




Reply via email to