Joe Ma Joe Ma - 6 months ago 13
Linux Question

Segmentation fault when called mosrcat() with 5 or above argment

#include <stdio.h>
#include <stdarg.h>
int mosrcat(char *o, int tsize, ...) {
strong textregister int cot = 0;
va_list ap;
char *t;
va_start(ap, tsize);
t = va_arg(ap, char *);
while(t != NULL) {
while((*(o++) = *(t++)) != 0) {
if(cot >= tsize) return -1;
t = va_arg(ap, char *);
return cot;

int main(void) {
char *t1 = "/lib/modules/";
char *t3 = "3.18.3-200.fc23.x86_64";
char *t5 = "/lib/modules/";
char *q = (char *)malloc(100 * sizeof(char));
mosrcat(q, 1000 ,t1, t3); //OK
mosrcat(q, 1000 ,t1, t3, t5); //Segmentation fault
return 0;

When I called mosrcat() with 5 or above arguments, it crushed. But NO PROBLEM with 4 arguments. In mosrcat() function, char point 'o' appear "" after the second loop. This expression is

while((*(o++) = *(t++)) != 0)

But 'o' always equal to "", not the value of 't'
How can I solve it?


As man says for va_arg function

If there is no next argument, or if type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), random errors will occur.

The problem is that va_arg doesn't return NULL for the first not passed parameter.You should pass NULL as additional parameter to use your algorithm.


    mosrcat(q, 1000 ,t1, t3, NULL);
    mosrcat(q, 1000 ,t1, t3, t5, NULL);

Or, as shown into @FlorinPetriuc answer, you can pass number of variable arguments you are passing to mosrcat function.

Other stuff are:

1) add #include <stdlib.h> to support malloc.

2) always check the malloc return: it can fail.

if (q != NULL)
    mosrcat(q, 1000 ,t1, t3, NULL);
    mosrcat(q, 1000 ,t1, t3, t5, NULL);

3) Last thing memory mallocated must be freed before program exits so

    return 0;