Ioannis said:
#include <stdlib.h>
char ***? Right (let me see what follows).
strlen() doesn't count '\0' (which always has the value 0 by the way). So
you must allocate one more character/byte.
The casting is not needed and sizeof(char) is always 1 byte. So you can make
it:
buffer = malloc(strlen(inbuffer)+1);
And in general do memory allocations like this:
some_type *p=malloc(some_length*sizeof(*p));
So you could do the above char
*buffer=malloc((strlen(inbuffer)+1)*sizeof(*buffer));
Of course you mean
buffer-malloc((
But since sizeof(*buffer)) is always 1 you can omit it.
if(buffer==NULL)
/* Do something */
Or better strncpy(buffer, inbuffer, strlen(inbuffer)+1); so as to be
protected from possible buffer overflows.
It is impossible to overflow buffer's allocated space. You allocated
strlen(inbuffer)+1. strcpy is safe.
(*outputarray) = (char**) malloc(100 * sizeof(char**));
outputarray is a temporary pointer variable containing a supposed value you
have passed from the calling function and apparently you are not using. Also
the char *** thing has no use here and the program in general is
non-sense...
argczwei = 0;
(*outputarray)[argczwei++] = strtok(buffer, ";");
while ((((*outputarray)[argczwei] = strtok(NULL, ";")) !=
NULL) ) ++argczwei;
(*outputarray)[argczwei+1] = NULL;
return argczwei;
free(buffer);
Call free() before return.
If you call free(buffer) in this function, the calling function cannot
use the array of pointers that was allocated. The pointers would
be pointing to space that has been freed. And, if you don't call
free(buffer) in this function then you have a memory leak. Therefore
the function has a design flaw. You can salvage most of the definition
if you change the protootype to:
char *inputneu(const char *inbuffer, char*** outputarray);
and making the changes in the definition. Still it is a rather
clumsy way to do it.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
char *inputneu(const char *inbuffer, char*** outputarray)
{
char* buffer;
int argczwei = 0;
if((buffer = malloc(strlen(inbuffer) + 1)) == NULL)
return NULL;
strcpy(buffer, inbuffer);
if((*outputarray = malloc(100 * sizeof(**outputarray)))
== NULL)
{
free(buffer);
return NULL;
}
(*outputarray)[argczwei++] = strtok(buffer, ";");
while (argczwei < 99 && ((*outputarray)[argczwei] =
strtok(NULL, ";")) != NULL ) ++argczwei;
(*outputarray)[argczwei] = NULL;
return buffer;
}
int main(void)
{
char *s ,**tok;
size_t count;
s = inputneu("John;Bill;Harry",&tok);
if(s)
{
for(count = 0;tok[count]; count++)
printf("tok[%u] = %s\n",count,tok[count]);
printf("There are %u strings in tok\n",count);
free(tok);
free(s);
}
return 0;
}