5

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));
}
user229044
  • 232,980
  • 40
  • 330
  • 338
zaz
  • 445
  • 1
  • 6
  • 12

2 Answers2

2

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, " ");
imreal
  • 10,178
  • 2
  • 32
  • 48
0

1) First of all

for(i = 0; str[i] != '\0'; )

this is wrong because str[i] is an address and not a char so you have to compare to a NULL address and not a null character. here after how to do it

for(i = 0; str[i] != NULL; )

2)Second Define space as following

char space = " ";

and then

 strcat(a, space);

and not

strcat(a, &space);

3) I do not know if xmalloc() is setting the allocated memory to 0. If not then you have to set the first element in the a array to '\0'.

a = (char *) xmalloc(num * sizeof(char));
a[0] = '\0';
MOHAMED
  • 41,599
  • 58
  • 163
  • 268
  • 4
    '\0' == 0 so this does not matter. – Intrepidd Nov 22 '12 at 18:37
  • code not propely writen. it would be better to advice him. the null for address is writen with NULL – MOHAMED Nov 22 '12 at 18:43
  • 32 bits zero will be equal to 8 bit zero if you compare the two values. – Intrepidd Nov 22 '12 at 18:58
  • This is C, so integer character constants have type `int`, thus `'\0'` is at least 16 bits, usually 32. `'\0'` is a constant expression evaluating to 0, so in pointer context, it is a null pointer constant. So `str[i] != '\0'` is valid there. But it's bad style, since it suggests a character comparison to the reader. – Daniel Fischer Nov 22 '12 at 19:16
  • Indeed Both you are right: http://stackoverflow.com/questions/1296843/what-is-the-difference-between-null-0-and-0 – MOHAMED Nov 22 '12 at 19:19