Splitting string with delimiters in C - segmentation fault - c

I want to write a function that will split a string into a char array. I know that the result array will ALWAYS have only two elements - servername and serverport. I wrote this, but it gives me "Segmentation fault" after compilation:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* splitString(char stringToSplit[])
{
int i = 0;
char serverinfo[2];
char *tmp;
tmp = strtok(stringToSplit, ":");
while (tmp != NULL)
{
serverinfo[i] = tmp;
tmp = strtok(NULL, ":");
i++;
}
return serverinfo;
}
int main(int argc, char **argv)
{
char st[] = "servername:1234";
char *tab = splitString(st);
printf("%s\n", tab[0]);
printf("%s\n", tab[1]);
return 0;
}

char serverinfo[2];
allocates space for two chars, but you store char*s there, so make it
char* serverinfo[2];
But you return it from the function, however, the local variable doesn't exist anymore after the function returned, so you need to malloc it
char **serverinfo = malloc(2*sizeof *serverinfo);
and declare the function as
char **splitString(char stringToSplit[])
for the correct type.

Related

return a modified array of char**

C- language——-Trying to call a function "test" from main(). This takes 3 arguments argc, argv and a pointer function which either turns the string into lower case or upper case. Then using the array of modified values i will just loop and print them.
I get segmentation fault error.
I want to return the entire array. So that in my main() i will loop through it and print it. How can i do this? Where am i going wrong in my code? Any help would be great.
Your codes have some incorrect points and are redundant as well.
You can try the below codes
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
char **test(int argc, const char *const *argv, int (*const chnge)(int)){
char **retArr = malloc((argc+1) * sizeof(char*));
for (int i = 0; i < argc; ++i) {
const char *str = argv[i];
int len = strlen(str);
char* transform = malloc((len+1) * sizeof(char));
for (int j = 0; j < (len+1); ++j) {
transform[j] = chnge(str[j]);
}
retArr[i] = transform;
}
retArr[argc] = NULL; // An array of char* terminated by NULL
return retArr;
}
int main(int argc, const char *const *argv) {
char **val1 = test(argc, argv, &toupper);
char **val2 = test(argc, argv, &tolower);
for (char *const *p = val1, *const *q = val2; *p && *q; ++argv, ++p, ++q) {
printf("[%s] -> [%s] [%s]\n", *argv, *p, *q);
free(*p);
free(*q);
}
free(val1);
free(val2);
}
I believe the answer may have to do with the fact that you are trying to directly act on a string 1. without using strcpy, and 2. using a pointer array (char*) instead of an array object (char[]) which can cause a segfault.
Sorry, this would better be suited to a comment and not an answer, but I unfortunately can't comment quite yet. This may be of help?

Duplicate function -> exited, segmentation fault ç_ç

I'm programming in C, I know why when I start my program, the terminal show me this error, but I don't know how to fix it (I have read many question about this, but no I can't solve this problem) :
My function is :
char * String_dup(char const string[]) {
size_t size = strlen(string);
char * copy = malloc(size * copy[0]);
assert(copy != NULL);
strcpy(copy, string);
return copy;
}
it consist to duplicate my string[].
And this is my test :
void StringTest_dup(void) {
char string[] = "voiture";
assert(strcmp(string, String_dup(string)));
}
Thank you for your help.
I re-wrote it a bit and it seems to work without a problem. One obvious misundertanding you have is that strcmp returns 1 when they match which is wrong. If the two inputs to strcmp are the same then it returns 0, thus !strcmp(...).
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
char* String_dup(const char* string) {
size_t size = strlen(string);
char* copy = malloc(size * sizeof(char) + 1);
assert(copy != NULL);
strcpy(copy, string);
return copy;
}
int main(void) {
const char* string = "test";
char* copy = String_dup(string);
assert(!strcmp(string, copy));
printf("%s\n", string);
printf("%s\n", copy);
free(copy);
return 0;
}

C: Splitting a string into two strings, and returning a 2 - element array

I am trying to write a method that takes a string and splits it into two strings based on a delimiter string, similar to .split in Java:
char * split(char *tosplit, char *culprit) {
char *couple[2] = {"", ""};
int i = 0;
// Returns first token
char *token = strtok(tosplit, culprit);
while (token != NULL && i < 2) {
couple[i++] = token;
token = strtok(NULL, culprit);
}
return couple;
}
But I keep getting the Warnings:
In function ‘split’:
warning: return from incompatible pointer type [-Wincompatible-pointer-types]
return couple;
^~~~~~
warning: function returns address of local variable [-Wreturn-local-addr]
... and of course the method doesn't work as I hoped.
What am I doing wrong?
EDIT: I am also open to other ways of doing this besides using strtok().
A view things:
First, you are returning a pointer to a (sequence of) character(s), i.e. a char
* rather than a pointer to a (sequence of) pointer(s) to char. Hence, the return type should be char **.
Second, you return the address of a local variable, which - once the function has finished - goes out of scope and must not be accessed afterwards.
Third, you define an array of 2 pointers, whereas your while-loop may write beyond these bounds.
If you really want to split into two strings, the following method should work:
char ** split(char *tosplit, char *culprit) {
static char *couple[2];
if ((couple[0] = strtok(tosplit, culprit)) != NULL) {
couple[1] = strtok(NULL, culprit);
}
return couple;
}
I'd caution your use of strtok, it probably does not do what you want it to. If you think it does anything like a Java split, read the man page and then re-read it again seven times. It is literally tokenizing the string based on any of the values in delim.
I think you are looking for something like this:
#include <stdio.h>
#include <string.h>
char* split( char* s, char* delim ) {
char* needle = strstr(s, delim);
if (!needle)
return NULL;
needle[0] = 0;
return needle + strlen(delim);
}
int main() {
char s[] = "Fluffy furry Bunnies!";
char* res = split(s, "furry ");
printf("%s%s\n", s, res );
}
Which prints out "Fluffy Bunnies!".
First of all strtok modifies the memory of tosplit so be certain that, that's what you wish to do. If so then consider this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
* NOTE: unsafe (and leaky) implementation using strtok
*
* *into must point to a memory space where tokens can be stored
* or if *into is NULL then it allocates enough space.
* Returns:
* allocated array of items that you must free yourself
*
*/
char **__split(char *src, const char *delim)
{
size_t idx = 0;
char *next;
char **dest = NULL;
do {
dest = realloc(dest, (idx + 1)* sizeof(char *));
next = strtok(idx > 0 ? NULL:strdup(src), delim);
dest[idx++] = next;
} while(next);
return dest;
}
int main() {
int x = 0;
char **here = NULL;
here = __split("hello,there,how,,are,you?", ",");
while(here[x]) {
printf("here: %s\n", here[x]);
x++;
}
}
You can implement a much safer and non leaky version (note the strdup) of this but hopefully this is a good start.
The type of couple is char** but you have defined the function return type as char*. Furthermore you are returning the pointer to a local variable. You need to pass the pointer array into the function from the caller. For example:
#include <stdio.h>
#include <string.h>
char** split( char** couple, char* tosplit, char* culprit )
{
int i = 0;
// Returns first token
char *token = strtok( tosplit, culprit);
for( int i = 0; token != NULL && i < 2; i++ )
{
couple[i] = token;
token = strtok(NULL, culprit);
}
return couple;
}
int main()
{
char* couple[2] = {"", ""};
char tosplit[] = "Hello World" ;
char** strings = split( couple, tosplit, " " ) ;
printf( "%s, %s", strings[0], strings[1] ) ;
return 0;
}

C: Take parts from a string without a delimiter (using strstr)

I have a string, for example: "Error_*_code_break_*_505_*_7.8"
I need to split the string with a loop by the delimiter "_*_" using the strstr function and input all parts into a new array, let's call it -
char *elements[4] = {"Error", "code_break", "505", "7.8"}
but strstr only gives me a pointer to a char, any help?
Note: the second string "code_break" should still contain "_", or in any other case.
This will get you half-way there. This program prints the split pieces of the string to the standard output; it does not make an array, but maybe you can add that yourself.
#include <stdio.h>
#include <string.h>
#include <malloc.h>
void split(const char * str, const char * delimiter)
{
char * writable_str = strdup(str);
if (writable_str == NULL) { return; }
char * remaining = writable_str;
while (1)
{
char * ending = strstr(remaining, delimiter);
if (ending != NULL) { *ending = 0; }
printf("%s\n", remaining);
if (ending == NULL) { break; }
remaining = ending + strlen(delimiter);
}
free(writable_str);
}
int main(void) {
const char * str = "Error_*_code_break_*_505_*_7.8";
const char * delimiter = "_*_";
split(str, delimiter);
return 0;
}
Here is a function that splits a string into an array. You have to pass the size of the array so that the function won't overfill it. It returns the number of things it put into the array. What it puts into the array is a pointer into the string that was passed. It modifies the string by inserting null characters to end the pieces - just like strtok does.
#include<string.h>
#include<stdio.h>
int split(char *string, char *delimiter, char* array[], int size)
{
int count=0;
char *current=string;
char *next;
while(current && *current!='\0')
{
next=strstr(current,delimiter);
if(!next)break;
*next='\0';
if(count<size) array[count++]=current;
current=next+strlen(delimiter);
}
if(count<size) array[count++]=current;
return count;
}
int main()
{
char string[100]="Error_*_code_break_*_505_*_7.8";
char *array[10];
int size=split(string,"_*_",array,10);
for(int i=0;i<size;i++) puts(array[i]);
return size;
}

C - Not getting the right value with an argument pointer

The get_current_path function gets a pointer to a char string of the current working directory. printf("%s\n", buf); in the function itself prints exactly what I want, but then outside of the function, printf("%s", thisbuf); gives me a lot of garbage. I assume I've made some silly mistake here, but I can't figure out what it is.
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <unistd.h>
int get_current_path(char *buf) {
long cwd_size;
char *ptr;
cwd_size = pathconf(".", _PC_PATH_MAX);
if ((buf = (char *) malloc((size_t) cwd_size)) != NULL)
ptr = getcwd(buf, (size_t)cwd_size);
else cwd_size == -1;
printf("%s\n", buf);
printf("%ld\n", cwd_size);
return cwd_size;
}
int main (int argc, char **argv)
{
char *thisbuf;
get_current_path(thisbuf);
printf("%s", thisbuf);
return 0;
}
You should pass a pointer to char *
int get_current_path(char **buf)
{
*buf = ...;
}
int main()
{
char *thisbuf;
get_current_path(&thisbuf);
}
Parameters in C are pass-by-value, which means that get_current_path can't change the value of "thisbuf" passed in by the caller.
To make the change, you would have to pass in a pointer to "thisbuf":
int get_current_path(char **resultBuf) {
char *buf = (char *) malloc((size_t) cwd_size);
...
*resultBuf = buf; // changes "thisbuf" in the caller
}
....
get_current_path(&thisbuf); // note - passing pointer to "thisbuf"
Try this instead:
int get_current_path(char **buf) {
*buf = something; // Set buf with indirection now.
And:
int main (int argc, char **argv)
{
char *thisbuf;
get_current_path(&thisbuf);
printf("%s", thisbuf);
return 0;
}
You were trying to pass a copy of buf to get_current_path, so when buf was modified, the original pointer to buf was not modified.

Resources