Cで文字列を分割する際に問題があります。コードを実行しようとするたびに、「セグメント化エラー」エラーが発生します。しかし、私は問題が何であるかはよく分かりません。C - 複数の部分に分割する文字列
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char** string_array = NULL; //string array for the split method
static int split_string(char* string, char* delimiter)
{
char* part = strtok(string, delimiter);//string which is getting split out by strtok
int number_of_parts = 0;//number of strings
/*split string into multiple parts*/
while(part)
{
string_array = realloc(string_array, sizeof(char*)* ++number_of_parts);
if(string_array == NULL)//allocation failed
return -1;
string_array[number_of_parts-1] = part;
part = strtok(NULL, delimiter);
}
/*write final null into string_array*/
string_array = realloc(string_array, sizeof(char*)* (number_of_parts+1));
string_array[number_of_parts] = 0;
return 0;
}
int main()
{
char* string = "string1 string2 string3";
printf("%d", split_string(string, " "));
return 0;
}
@ n.m。合意したが、OPがこの参照を見つけるのは難しい。 –
再割り当てに失敗した場合、 'old_ptr = realloc(old_ptr、new_size)'構造はメモリをリークすることに注意してください。あなたは 'void * new_ptr = realloc(old_ptr、new_size);を使う必要があります。 if(new_ptr == 0){...ハンドルエラー...} old_ptr = new_ptr; '。そうすれば、まだ解放できる 'old_ptr'に有効なポインタがあります。 –