here is my two functions :
void base(char *str)
{
char *without_spaces;
without_spaces = remove_spaces(str);
printf("Without spaces length : %d \n", strlen(without_spaces)); // SEGFAULT HERE !
free(without_spaces);
}
char *remove_spaces(char *source)
{
char *result;
int i = 0;
result = malloc(strlen(source) + 1);
while (*source != 0)
{
if (*source != ' ') {
result[i] = *source;
i++;
}
source++;
}
result[i] = '\0';
// If I make the printf here it's work's
return (result);
}
Here is how I call the base function (the chars provide from the stdin)
int main()
{
unsigned int maxsize = 324220;
unsigned int size;
char *str;
char buffer[8096];
unsigned int i;
unsigned int p;
if ((str = malloc(maxsize + 1)) == NULL)
return (my_error(RUNTIME_ERROR_MSG, RUNTIME_ERROR_MEMORY));
p = 0;
while (p < maxsize && (size = read(0, buffer, 8096)) > 0)
{
i = 0;
while (i < size && p < maxsize)
{
str[p] = buffer[i];
i = i + 1;
p = p + 1;
}
}
str[p] = '\0';
base(str);
return (0);
}
There are an segfault when I use this code with a really big str (approximately 500 000 chars) but it's works when I use it with less chars (like 50 000).
Why ? It's works if I remove the printf in the base function and make it in the remove space function like I have commented it.
Thank's ;)
EDIT: here it's valgrind output (with -g flag compiled)
==27259== Memcheck, a memory error detector
==27259== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==27259== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==27259== Command: ../a.out
==27259==
Without spaces length : 324987
==27259== HEAP SUMMARY:
==27259== in use at exit: 324,221 bytes in 1 blocks
==27259== total heap usage: 3 allocs, 2 frees, 649,466 bytes allocated
==27259==
==27259== LEAK SUMMARY:
==27259== definitely lost: 324,221 bytes in 1 blocks
==27259== indirectly lost: 0 bytes in 0 blocks
==27259== possibly lost: 0 bytes in 0 blocks
==27259== still reachable: 0 bytes in 0 blocks
==27259== suppressed: 0 bytes in 0 blocks
==27259== Rerun with --leak-check=full to see details of leaked memory
==27259==
==27259== For counts of detected and suppressed errors, rerun with: -v
==27259== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
stris properly NULL-terminated?malloc()before you use it? It can fail and return NULL — but your code assumes it is valid. It is possible that your system won't let you allocate 0.5 MiB of data, though it is unusual. Or you have some other operation that is messing up the heap from whichmalloc()allocates its data.valgrindoutput doesn't show a seg fault, so it isn't of any direct relevance to the question. The interestingvalgrindoutput would be from a run where the program crashes with the segmentation fault.valgrindon this machine at the moment, sadly.)