Hi,
For the following code segment I am getting segmentation fault:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* trim(char* str)
{
// while consecutive ws at the beginning skip
int len = strlen(str);
int i = 0,j = len-1,k,l = 0;
while (str[i] == ' ' || str[i] == '\t' || str[i] == '\n' || str[i] == '\r') i++;
// while consecutive ws at the end skip
while (str[j] == ' ' || str[j] == '\t' || str[j] == '\n' || str[j] == '\r') j--;
printf("i: %d, j: %d, len: %d\n",i,j,len);
for (k = i;k <= j;k++)
{
str[l++] = str[k];
}
str[l] = '\0';
printf("str: %s %d\n",str, strlen(str));
}
int main()
{
char* str = (char*)malloc(10*sizeof(char));
strcpy(str," abc \n");
printf("str: %s\n",str);
str = trim(str);
printf("str: %s\n",str);
return 0;
}
str: abc
i: 4, j: 6, len: 9
str: abc 3
Segmentation fault
In this example *str in the trim is the same as the pointer *str in main (pointing to the same location). So I dont understand how come I get a segmentation fault.
In general it always baffles me what happens when a pointer is returned from within a function called by another function.