这是我的两个函数:
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] = ' ';
// If I make the printf here it's work's
return (result);
}
下面是我如何调用基函数(字符从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] = ' ';
base(str);
return (0);
}
有一个段错误,当我使用这段代码与一个非常大的str(大约500000字符),但它的工作,当我使用它与更少的字符(如50000)。
为什么?如果我在基本函数中删除printf,并使其在删除空间函数中,就像我已经注释过它一样,它是有效的。
谢谢;)
编辑:这里是valgrind输出(编译了-g标志)
==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)
我认为这些函数在逻辑上有点混乱,读取的函数也会进行复制,我更喜欢一种方法,其中有一个函数来计算malloc的良好长度,然后一个复制,最后一个从stdin读取
#include <stdlib.h>
#include <stdio.h>
static size_t ft_strlen(const char *str)
{
size_t len;
len = 0;
while (*str != ' ')
{
if (*str != ' ')
len++;
str++;
}
return (len);
}
char *delete_spaces(const char *str)
{
const size_t size = ft_strlen(str);
char *nospaces;
size_t p;
if (!(nospaces = malloc(size + 1)))
return (NULL);
p = 0;
while (*str)
{
if (*str != ' ')
nospaces[p++] = *str;
str++;
}
nospaces[p] = ' ';
return (nospaces);
}
int main(int ac, char **av)
{
char *nospaces;
if (ac < 2)
return (0);
nospaces = delete_spaces(av[1]);
printf("nospaces: %sn", nospaces);
free(nospaces);
return (0);
}
/a。跳出"测试带有一些空格的字符串"给出:nospaces: testingastringwithsomeesspaces
那么在这种情况下,您也将malloc正好是合适的大小(source - number of空格+ 1)
如果你使用clang编译,你可以添加:-fsanitize =地址g3
到编译标志使用- everything -Werror在查找此类bug时,