Hi, first post here
I'm writing a program in C on Linux (Ubuntu) for a school project, one of the modules of the program is getting two arguments (patt and repl) and is also taking lines from stdin (using getline()) and must replace every occurrence of patt with repl.
Two problems:
A. I get segmentation faults when I'm trying to free the pointer allocated by getline()
B. Even if I comment out that free() statement, the string I get after running the replace function is printed as if no replacement occured! I'm passing a pointer to that string to the replacing function.
here's the short version of the code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int strreplace(char *str, char *patt, char *repl);
int main(int argc, char** argv) {
char *str; //replace pattern
size_t rsize; //num of read files by getline()
int nbytes;
char *patt = argv[1]; //pattern to look for
char *repl = argv[2]; //replace found pattern with this
str = NULL; //getline() needs NULL and 0 in order to allocate new mem
rsize = 0;
//getline() allocates the need memory for the line in to *str
//it is user's responsibility to free() the allocated mem
if((nbytes = getline(&str, &rsize, stdin)) < 0) { //end of file
exit(1);
}
if( argc == 3 && (strstr(str, patt) != NULL) ) {
strreplace(str, patt, repl); //this function replaces patt with repl
printf("str: %s", str);
}
return (EXIT_SUCCESS);
}
int strreplace(char *str, char *patt, char *repl) {
char *occ = NULL; //ptr to first char of first occurence of the pattern in str
char *temp; //temp string to hold str
int poss, pose; //poss - pos of the first char of patt in str, pose - after last char of patt
int diff = (strlen(repl) - strlen(patt));
int tempsize;
while((occ = strstr(str, patt)) != NULL) {
tempsize = strlen(str) + diff + 1;
temp = (char*)malloc(sizeof(char)*(tempsize));
poss = strlen(str) - strlen(occ); //getting the pos of the first char of patt in str
pose = poss + strlen(patt); //getting pos of the char after last char of patt in str
memcpy(temp, str, poss);
memcpy(temp + poss, repl, strlen(repl));
memcpy(temp + poss + strlen(repl), str + pose, strlen(&(str[pose])));
temp[tempsize] = '\0';
free(str); // here I get the seg.fault if i don't comment this out
str = (char*)malloc(sizeof(char)*tempsize);
memcpy(str, temp, tempsize);
free(temp);
//printf("-----\nstr: %s strlen: %d\n------\n", str, strlen(str));
}
return 0; //success
}
Thanx
ps. I've also posted this question on the Ubuntu forums (no answer yet )
http://ubuntuforums.org/showthread.php?t=1022846