Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my function cause a segfault when called from within a library?

Tags:

c

This code converts a vector(argv) to a string, and prints it. However, if the vect2str is called from a library(my_vect2str), it gives a warning:

warning: passing argument 1 of ‘puts’ makes pointer from integer without a cast

And segfaults when ran. The function vect2str here is the exact same as the one in the library(my_vect2str). The library was compiled on the same computer.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "../lib/my.h"

char *vect2str(char **str) {

if (str == NULL)
    return NULL;
if (*str == NULL)
    return NULL;

int num = 0;
char * a;

int i;
for(i = 0; str[i] != '\0'; )
    num += strlen(str[i++]);

num += i;
a = (char *) xmalloc(num * sizeof(char));

//Make new string
char space = ' ';
char *end = "";

int j;
for(j = 0; str[j] != NULL; j++) {
    strcat(a, str[j]);
    strcat(a, &space);
    }
strcat(a, end);
return a;
}

int main(int argc, char **argv) {

puts(vect2str(argv));

//This does not work
//puts(my_vect2str(argv));
}
like image 347
zaz Avatar asked Nov 03 '22 10:11

zaz


1 Answers

It compiles fine on cygwin and puts receives a char pointer alright.
The problem I saw is that you are doing a strcat with a pointer to a single character.

strcat(a, &space);

The way strcat works is by copying from one string to another until it finds a terminating null character ('\0'), if you don't supply a string with one, strange things can happen, change it for this:

strcat(a, " ");
like image 197
imreal Avatar answered Nov 15 '22 05:11

imreal