I am a beginner C developer.
Each line of the input file must be split into words (token) according a space delimiter and each token stored in an array.
The problematic function is the following
Code:
char *str2array (char *p_buffer, ssize_t count)
{
char *p_array = NULL;
char *p_token = NULL;
char delimiters[] = " \t";
if (count > 0)
{
p_array = malloc (count + 1);
if (p_array != NULL)
{
printf ("-> malloc=%p\n", p_array);
printf (" p_buffer=%p\n", p_buffer);
p_token = strtok (p_buffer, delimiters);
for (int i = 0; p_token != NULL; i++)
{
printf (" p_token=%p\n", p_token);
printf (" array[%d]=%p\n", i, &(p_array[i]));
p_token = strtok (NULL, delimiters);
}
}
}
return p_array;
}
Below the result of the first lines
Code:
$ ./prog.exe
-> malloc=0x600048c90
p_buffer=0x600000480
p_token=0x600000480
array[0]=0x600048c90
p_token=0x600000486
array[1]=0x600048c91
p_token=0x60000048f
array[2]=0x600048c92
-> malloc=0x600048c90
p_buffer=0x600000480
p_token=0x600000480
array[0]=0x600048c90
p_token=0x600000485
array[1]=0x600048c91
-> malloc=0x600048c90
p_buffer=0x600000480
p_token=0x600000480
array[0]=0x600048c90
p_token=0x600000485
array[1]=0x600048c91
Coresponding to the 3 first records
Code:
START ANALYSIS 1
DATA LINE
DATA LINE
I do not see where my mistakes are:
- For example, the first token of the first line has a length of 5+1 characters, and the second token of the first line has a length of 8+1 characters.
'p_array' memory address progression is only 1 character each time. So I badly increment each element of the array.
Can you, please, help me to correct this code ?
For a moment I don't try to stock anything in the array because I am not able to correctly reference each item of it.