Autor Tópico: ajuda com esse programa [ c ]  (Lida 2666 vezes)

Offline _Luks

  • Usuário Ubuntu
  • *
  • Mensagens: 202
  • Debian Lenny
    • Ver perfil
    • Meu Blog
ajuda com esse programa [ c ]
« Online: 27 de Maio de 2007, 23:49 »
o erro se encontra na função **get_tokens, na parte tk = strtok(str,space);

por que está dando segfault ?

Código: [Selecionar]
# include <stdio.h>
# include <string.h>
# include <stdlib.h>

int count_tokens(char str[], char space[])
{
char *tk = NULL;
int ct;
tk = strtok(str," ");

while (tk)
{
ct++;
tk = strtok(NULL,space);
}

free(tk);

return ct;
}

char **get_tokens(char str[],char space[],int size)
{
int i;
int str_len = 500;
char *tk = NULL;
char **tokens;

tokens = malloc(size*sizeof(char)); //alocando memoria pro *tokens

tk = strtok(str,space);

for (i = 0 ; i < size ; i++ )
{
tokens[i] = malloc(str_len*sizeof(char));

if (!i) strcpy(tokens[i],tk);
tk = strtok(NULL,space);
puts(tk);
strcpy(tokens[i],tk);
}

return tokens;
}

void main()
{

char s[] = "a b c d e f g";
int count,i;
char **tks;

count = count_tokens(s," ");
tks = get_tokens(s," ",count);
}

Offline Diego_Rocha

  • Usuário Ubuntu
  • *
  • Mensagens: 372
  • Slackware current
    • Ver perfil
Re: ajuda com esse programa [ c ]
« Resposta #1 Online: 28 de Maio de 2007, 00:20 »
Código: [Selecionar]
int count_tokens(char str[], char space[])
{
char *tk = NULL;
int ct;
tk = strtok(str," ");

while (tk)
{
ct++;
tk = strtok(NULL,space);
}

free(tk);

return ct;
}

tu não reservou memoria com malloc para usar o free(); e sempre que der segmentation fault usa o gdb pra debugar e ve em qual função ta o erro t++