null terminate an array of strings - c

I am trying to figure out how to get my array of strings from get_arguments to NULL terminate, or if that isn't the issue to function in my execv call.
char ** get_arguments(const char * string) {
char * copy = strdup(string);
char * remove_newline = "";
for(;;) {
remove_newline = strpbrk(copy, "\n\t");
if (remove_newline) {
strcpy(remove_newline, "");
}
else {
break;
}
}
char (* temp)[16] = (char *) malloc(256 * sizeof(char));
char * token = strtok(copy, " ");
strcpy(temp[0], token);
int i = 1;
while (token && (token = strtok(NULL, " "))) {
strcpy(temp[i], token);
i++;
}
char * new_null;
//new_null = NULL;
//strcpy(temp[i], new_null);
if(!temp[i]) printf("yup\n");
int c = 0;
for ( ; c <= i; c++) {
printf("%s ", temp[c]);
}
return temp;
}
I am trying to read in a string, space separated, similar to find ./ -name *.h. I am trying to input them into execv.
char (* arguments)[16] = (char **) malloc(256 * sizeof(char));
//...numerous lines of unrelated code
pid = fork();
if (pid == 0) {
arguments = get_arguments(input_string);
char * para[] = {"find", "./","-name", "*.h", NULL};
execv("/usr/bin/find", (char * const *) arguments);
//printf("%s\n", arguments[0]);
printf("\nexec failed: %s\n", strerror(errno)); //ls -l -R
exit(-1);
}
When I swap arguments in the execv call for para it works as intended, but trying to call with arguments returns exec failed: Bad address. If I remove the NULL from para I get the same issue. I've tried strcpy(temp, (char *) NULL), the version you see commented out in get_arguments, and a number of other things that I can't recall in their entirety, and my program ranges from Segmentation fault to failure to compile from attempting to strcpy NULL.
Changing the declarations of arguments and temp to char ** arguments = (char *) malloc(256 * sizeof(char)); ``char ** temp = (char *) malloc(256 * sizeof(char));clears upwarning: initialization from incompatible pointer typebut causes segfault on all calls toget_arguments`.

You want this:
char* temp[256]; // an array of 256 char*'s
char * token = strtok(copy, " ");
temp[0] = strdup(token);
int i = 1;
while (token && (token = strtok(NULL, " "))) {
temp[i] = strdup(token);
i++;
}
temp[i] = NULL;

Related

Function to split a string and return every word in the string as an array of strings

I am trying to create a function that will accept a string, and return an array of words in the string. Here is my attempt:
#include "main.h"
/**
* str_split - Splits a string
* #str: The string that will be splited
*
* Return: On success, it returns the new array
* of strings. On failure, it returns NULL
*/
char **str_split(char *str)
{
char *piece, **str_arr = NULL, *str_cpy;
int number_of_words = 0, i;
if (str == NULL)
{
return (NULL);
}
str_cpy = str;
piece = strtok(str_cpy, " ");
while (piece != NULL)
{
if ((*piece) == '\n')
{
piece = strtok(NULL, " ");
continue;
}
number_of_words++;
piece = strtok(NULL, " ");
}
str_arr = (char **)malloc(sizeof(char *) * number_of_words);
piece = strtok(str, " ");
for (i = 0; piece != NULL; i++)
{
if ((*piece) == '\n')
{
piece = strtok(NULL, " ");
continue;
}
str_arr[i] = (char *)malloc(sizeof(char) * (strlen(piece) + 1));
strcpy(str_arr[i], piece);
piece = strtok(NULL, " ");
}
return (str_arr);
}
Once I compile my file, I should be getting:
Hello
World
But I am getting:
Hello
Why is this happening? I have tried to dynamically allocate memory for the new string array, by going through the copy of the original string and keeping track of the number of words. Is this happening because the space allocated for the array of strings is not enough?
The code seems fine overall, with just some issues:
You tried to copy str, as strtok modifies it while parsing.
This is the right approach. However, the following line is wrong:
str_cpy = str;
This is not a copy of strings, it is only copying the address of the string. You can use strdup function here.
Also, you need to return the number of words counted otherwise the caller will not know how many were parsed.
Finally, be careful when you define the string to be passed to this function. If you call it with:
char **arr = str_split ("Hello World", &nwords);
Or even with:
char *str = "Hello World";
char **arr = str_split (str, &nwords);
The program will crash as str here is read-only (see this).
Taking care of these, the program should work with:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/**
* str_split - Splits a string
* #str: The string that will be splited
*
* Return: On success, it returns the new array
* of strings. On failure, it returns NULL
*/
char **str_split(char *str, int *number_of_words)
{
char *piece, **str_arr = NULL, *str_cpy = NULL;
int i = 0;
if (str == NULL)
{
return (NULL);
}
str_cpy = strdup (str);
piece = strtok(str_cpy, " ");
while (piece != NULL)
{
if ((*piece) == '\n')
{
piece = strtok(NULL, " ");
continue;
}
(*number_of_words)++;
piece = strtok(NULL, " ");
}
str_arr = (char **)malloc(sizeof(char *) * (*number_of_words));
piece = strtok(str, " ");
for (i = 0; piece != NULL; i++)
{
if ((*piece) == '\n')
{
piece = strtok(NULL, " ");
continue;
}
str_arr[i] = (char *)malloc(sizeof(char) * (strlen(piece) + 1));
strcpy(str_arr[i], piece);
piece = strtok(NULL, " ");
}
if (str_cpy)
free (str_cpy);
return (str_arr);
}
int main ()
{
int nwords = 0;
char str[] = "Hello World";
char **arr = str_split (str, &nwords);
for (int i = 0; i < nwords; i++) {
printf ("word %d: %s\n", i, arr[i]);
}
// Needs to free allocated memory...
}
Testing:
$ gcc main.c && ./a.out
word 0: Hello
word 1: World

C - Trying to build a simple shell in linux and having trouble with strtok, realloc in a loop

Trying to build a shell implementation in linux for an assignment and am having trouble. I get the following error after running 3/4 times into the loop
* Error in `./1': realloc(): invalid next size: 0x000000000132c150 *
Aborted (core dumped)
I have left parts of the code out as it's long and I know there's no issues with them. If there's other parts you need I can add them too.
Thanks in advance :)
Note: argc and argv are global variables
int argc = 0;
char **argv = NULL;
int main(void)
{
while(1)
{
catch_signal();
printDate();
readCommand();
if(strcmp(argv[0], "cd") == 0)
{
changeDirectory();
}
else
{
executeCommand();
}
//free(argv);
}
}
void readCommand()
{
char *buffer = NULL;
char *token = " ";
char *p;
size_t len = 0;
int i = 0;
getline(&buffer, &len, stdin);
p = strtok(buffer, "\n");
p = strtok(buffer, token);
while(p)
{
argv = realloc(argv, sizeof(char *) * ++i);
argv[i - 1] = p;
p = strtok(NULL, token);
}
argc = i;
argv[argc] = NULL;
free(p);
}
void executeCommand()
{
int status;
pid_t pid;
if((pid = fork()) < 0)
{
printf("Error: forking child process failed.");
}
else if(pid == 0)
{
if(execvp(argv[0], argv) < 0)
{
printf("error");
exit(1);
}
}
else
{
while(wait(&status) != pid);
}
}
You are reallocating the argv array 1 pointer too short. There is not enough space for the final NULL pointer. Consider replacing the while(p) loop with this code:
if (!p) {
/* deal with empty command line */
}
while (p) {
argv = realloc(argv, sizeof(char *) * (i + 2));
argv[i++] = p;
p = strtok(NULL, token);
}
p should start as NULL if the user entered an actual command. But what if buffer contains an empty string or just a blank one? strtok will return NULL directly in these cases. You should ignore such command lines.

Weird seg faults on consecutive calls to the same array

I tried really hard to search for a solution to this but I can't think of good enough keywords.
Currently I'm having troubles grasping the concept behind makeargv and it's usage with triple pointers (I have no idea what ***foo means, it doesn't seem to be as easy of a concept as **foo or *foo). So I made my own:
const char **makeargv(char *string, int *numargs) {
string = string + strspn(string, delims);
char *copy = malloc(strlen(string) + 1);
int i;
strcpy(copy, string);
int numtokens;
if (strtok(copy, delims) != NULL) {
for (numtokens = 1; strtok(NULL, delims) != NULL; numtokens++) {}
}
strcpy(copy, string);
const char *results[numtokens+1];
results[0] = strtok(copy, delims);
for (i = 1; i < numtokens; i++) {
results[i] = strtok(NULL, delims);
}
results[numtokens+1] = NULL;
*numargs = numtokens;
return results;
}
Here's the part at where it breaks:
void parse_file(char* filename) {
char* line = malloc(160*sizeof(char));
FILE* fp = file_open(filename);
int i = 0;
int numargs = 0;
int *pointer = &numargs;
while((line = file_getline(line, fp)) != NULL) {
if (strlen(line) == 1){
continue;
}
const char **args = makeargv(line, pointer);
printf("%s\n", args[0]);
printf("%s\n", args[1]);
/* This prints out args[0], but then args[1] causes a seg fault. Even if I replace
the args[1] with another args[0] it still causes a seg fault */
}
fclose(fp);
free(line);
}
I have a working array of strings. However when I try to print out the strings in the array, I can only print 1 of my choice and then it seg faults for any subsequent calls. lets pretend my array of strings is argv[3] = {"Yes", "no", "maybe"}, if i call argv[0], it will let me call "Yes", but any other calls (even if i call argv[0] again) do not work and cause a segfault. I can call any of the elements in the array, but once i call one the rest cease to work causing segfaults.
Help please? D: This is in C.
const char *results[numtokens+1];
This array "results" is a local variable, it is only available inside of "makeargv".
You'd better use malloc:
results = malloc(numtokens+1)
And I believe there is memory leak in your code.
You will not be able to free the memory for "char *copy"
char *copy = malloc(strlen(string) + 1);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **makeargv(char *string, int *numargs) {
static const char *delims = " \t\n";
string = string + strspn(string, delims);
char *copy = malloc(strlen(string) + 1), *p = copy;
strcpy(copy, string);
int numtokens;
for (numtokens = 0; strtok(p, delims); ++numtokens, p = NULL);
char **results = malloc(sizeof(char*)*(numtokens+1));
strcpy(copy, string);
int i;
p = copy;
for (i = 0; i < numtokens; ++i, p = NULL)
results[i] = strtok(p, delims);
results[i] = NULL;
*numargs = numtokens;
return results;
}
FILE *file_open(char *filename){
FILE *fp = fopen(filename, "r");
if(!fp){
perror("file_open");
exit(1);
}
return fp;
}
void parse_file(char* filename) {
char* line = malloc(160*sizeof(char));
FILE* fp = file_open(filename);
int i = 0, numargs = 0;
while(fgets(line, 160, fp)){
if (*line == '\n')
continue;
char **args = makeargv(line, &numargs);
for(i = 0;i<numargs;++i)
printf("%s\n", args[i]);
printf("\n");
if(args[0])
free(args[0]);
free(args);
}
fclose(fp);
free(line);
}
int main(int argc, char *argv[]){
parse_file(argv[1]);
return 0;
}

In C, How to split a string on \n into lines

I want to split a string by \n and place lines which contain a specific token into an array.
I have this code:
char mydata[100] =
"mary likes apples\njim likes playing\nmark hates school\nanne likes mary";
char *token = "likes";
char ** res = NULL;
char * p = strtok (mydata, "\n");
int n_spaces = 0, i;
/* split string and append tokens to 'res' */
while (p) {
res = realloc (res, sizeof (char*) * ++n_spaces);
if (res == NULL)
exit (-1); /* memory allocation failed */
if (strstr(p, token))
res[n_spaces-1] = p;
p = strtok (NULL, "\n");
}
/* realloc one extra element for the last NULL */
res = realloc (res, sizeof (char*) * (n_spaces+1));
res[n_spaces] = '\0';
/* print the result */
for (i = 0; i < (n_spaces+1); ++i)
printf ("res[%d] = %s\n", i, res[i]);
/* free the memory allocated */
free (res);
But then I get a segmentation fault:
res[0] = mary likes apples
res[1] = jim likes playing
Segmentation fault
How can I split a string on \n correctly in C?
strstr just returns a pointer to the first match of second argument.
Your code is not taking care of null character.
Can use strcpy to copy string.
while (p) {
// Also you want string only if it contains "likes"
if (strstr(p, token))
{
res = realloc (res, sizeof (char*) * ++n_spaces);
if (res == NULL)
exit (-1);
res[n_spaces-1] = malloc(sizeof(char)*strlen(p));
strcpy(res[n_spaces-1],p);
}
p = strtok (NULL, "\n");
}
Free res using:
for(i = 0; i < n_spaces; i++)
free(res[i]);
free(res);
Try this:
char mydata[100] = "mary likes apples\njim likes playing\nmark hates school\nanne likes mary";
char *token = "likes";
char **result = NULL;
int count = 0;
int i;
char *pch;
// split
pch = strtok (mydata,"\n");
while (pch != NULL)
{
if (strstr(pch, token) != NULL)
{
result = (char*)realloc(result, sizeof(char*)*(count+1));
result[count] = (char*)malloc(strlen(pch)+1);
strcpy(result[count], pch);
count++;
}
pch = strtok (NULL, "\n");
}
// show and free result
printf("%d results:\n",count);
for (i = 0; i < count; ++i)
{
printf ("result[%d] = %s\n", i, result[i]);
free(result[i]);
}
free(result);

how to remove extra spaces from string in C

I have an string that have an extra spaces string, for example:
char * s = " foo baa ";
I want to conver it to:
foo baa
I have wrote this function:
void trim (char ** src)
{
char * p = strdup(* src);
char * ret = malloc(strlen(*src) + 1);
assert(ret != NULL);
char * token;
token = strtok(p, " \t");
while( NULL != token ) {
while (*token) {
*(ret ++) = *(token ++);
}
token = strtok(NULL, " \t");
}
printf("ret = %s\n", ret);
}
but it given for me an empty string from ret variable value. someone may point out my mistake? thanks in advance.
You are incrementing ret in your while, store the original address or use subscript to access different chars of ret.
// snip
char * ret = malloc(strlen(*src) + 1);
assert(ret != NULL);
char * ret_start = ret;
//snap
printf("ret_start = %s\n", ret_start);
Other naive solution in c++(can be easily changed to c code )----- :)
initially count=0 and str-> your c++ string
for(i=0;i< str.size();i++)
{
if(str[i]!=' ')
{
str[j++]=str[i];
count=0;
}
else if(str[i]==' '&&count==0)
{
str[j++]=str[i];
count =1;
}
}

Resources