Welcome to HBH! If you have tried to register and didn't get a verification email, please using the following link to resend the verification email.

Function keeps triggering Segmentation Faults.


ghost's Avatar
0 0

I'm trying to write a function that will select the first word from a string. It compiles fine, but whenever I run it a segmentation fault is triggered. This code is written in C and compiled with DevC/C++. Any suggestions or help is appreciated.

//Prototype char *word(char *str1, char *str2);

int main() {

char *test_str = "Monday Tuesday";
char *result;

word(test_str, result);

printf("%s\n", result);
getchar();

return 0;

}

//Function Definition char *word(char *str1, char *str2) {

  int x = 0;
  char space = ' ';
  
  while (str1[x] != space) { 
        str2[x] = str1[x];
        x = x + 1;
        }
  
  getchar();
  return str2;

};


ghost's Avatar
0 0
while (str1[x] != space) {
str2[x] = str1[x];
x = x + 1;
}```

I'm punching in your code to test it right now, but I'm pretty sure that's the problem. C deosn't work like that.

EDIT: A side note, if you're going to increment "x" at the end, you may as well use a for loop.

ghost's Avatar
0 0
lloh@Lucy:~$ gcc -o lulz lulz.c
lulz.c: In function ‘main’:
lulz.c:13: error: request for member ‘result’ in something not a structure or union```

I also get this, which means that your "word" function is fucking up the data it returns to the format string.

ghost's Avatar
0 0

I do not code in C but should you not have said:

#include <stdio.h>
...

ghost's Avatar
0 0

SwartMumba wrote: I do not code in C but should you not have said:

#include <stdio.h>
...

Yes, that too, exactly. But, I put that on top of his code, and I'm still getting these errors.


ghost's Avatar
0 0

The program compiles for me but it crashes. I think it is going in an endless loop or something.


ghost's Avatar
0 0

Here is a quick fix that works. I will post something better in a moment (I just need to go learn what I want to do). Like I said, "I don't know C."

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

//Prototype
void word(char *str1);

int main() {

char test_str[] = "Monday Tuesday";

word(test_str);

getchar();
return 0;

}

//Function Definition
void word(char *str1) {

char *SpaceIndex=strchr(str1,' ');
int index = SpaceIndex-str1+1;

for (int i=0; i < index; i++){
printf("%c", str1[i]);
}

};


ghost's Avatar
0 0

Yeah, SmartMumba's got it (very nice ;D).

markupchar test_str[] = "Monday Tuesday";

This is one critical thing you were missing, if the char isn't initially declared as an array, then you won't be able to loop through it as an array.


mido's Avatar
Member
0 0

Edit : Sorry, I didn't see that it had been solved.


The problem is in this line :

str2[x] = str1[x];

Unhandled exception at 0x00411488 in test.exe: 0xC0000005: Access violation writing location 0x00000008. str2[x] = str1[x];

Read this, may help :

http://blogs.msdn.com/chappell/archive/2005/01/12/351856.aspx