my good friend Mr Seg Fault
Hi all.
I am trying to store words beginning with "brown" into an array of structures, from the string: "Do cows have "brown" legs? How now "brownone" cow. A cow has four "brownthree" legs." I want to exclude words that only consist of "brown". I want string1 to be reduced with each search for "brown", and then a new search is done on the new reduced string.
So after the first "brown"(which I don't want stored), the new string to search for the next instance of "brown" is: "into an array of structures, from the string: Do cows have "brown" legs? How now "brownone" cow. A cow has four "brownthree" legs." And so on.
So I expect the output(when I print out the array of structures) to be:
Code:
brownone
brownthree
The debugger is giving a seg fault at line 35: strcpy(string1, temp_string), which leads me to believe that temp_string is larger than the memory allocated to string1. But even if I increase the memory allocated to string1 by an extra 100 chars(which is larger than the entire original string), still a seg fault. This is my first time using realloc(in this case to decrease memory), so did I make a mistake somewhere?
Thanks in advance.
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct strings {
char *string1;
int x;
};
int main(void)
{
struct strings data[10];
char * temp_string;
char * string1 = "Do cows have \"brown\" legs? How now \"brownone\" cow. A cow has four \"brownthree\" legs.";
char * search_string = "brown";
int loc; // location of matching word in string
char * word; // pointer to matching word
int len_string, len_search_string, ch = 0, array_ctr = 0, buffer_ctr = 0;
size_t len_temp_string;
puts(string1);
len_string = strlen(string1);
len_search_string = strlen(search_string);
printf("len_search-string = %d\n", len_search_string);
while((word = strstr(string1, search_string)) != NULL)
{
loc = word - string1;
printf("loc = %d", loc);
if((ch = string1[loc + len_search_string]) == '"') // to move to next char after end of search_string
{
len_temp_string = strlen(&string1[loc + len_search_string + 1]); // + 1 is to move past the "
temp_string = malloc(len_temp_string * sizeof(char));
strcpy(temp_string, &string1[loc + len_search_string + 1]); // +1 is to move past the "
string1 = realloc(string1, len_temp_string); // reallocate string1 to the length of the temp string
strcpy(string1, temp_string);
puts(string1);
continue;
}
else
{
while((ch = string1[loc]) != '"');
{
data[array_ctr].string1 = malloc(15 * sizeof(char));
data[array_ctr].string1[buffer_ctr] = ch;
loc++;
buffer_ctr++;
}
loc++;
data[array_ctr].string1[buffer_ctr] = '\0';
array_ctr++; // increment array to accept next word
buffer_ctr = 0; // reset
len_temp_string = strlen(&string1[loc]);
strcpy(temp_string, &string1[loc]);
string1 = realloc(string1, len_temp_string);
strcpy(string1, temp_string);
continue;
}
}
return 0;
}