user1796976
user1796976

Reputation: 5

How to use strcat with a char* of an unspecified length

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

char* changeString(char *inputString);

int main() {
   printf("Changed string is %s\n", changeString("42"));
}

char* changeString(char *inputString) {
    static const char* someStrings[3] = {"abc", "def", "ghi"};
    char* output;
    strcat(output, someStrings[1]);
    return output;
}

I'm trying to append a char* to another char* however the strcat keeps resulting in a segmentation fault because the char* has no size, changing char* output; to char output[100]; fixes the segmentation fault, but then I am returning the wrong type and I can't print the answer in printf.

Any advice would be much appreciated.

EDIT: I know the example above seems to do nothing of value, I changed it to demonstrate the logic I am using.

Upvotes: 0

Views: 2809

Answers (4)

Jong
Jong

Reputation: 9125

The variable output does not point to anything and has an undefined value. The error you receive is because you're trying to write to that unknown address.

First you must allocate some memory for the output string.

Upvotes: 1

ShinTakezou
ShinTakezou

Reputation: 9681

You can dynamically allocate memory, or keep a static storage you can pass to the caller (but then your program won't be thread safe, if you care).

   static char output[100];

Upvotes: 1

Bart Friederichs
Bart Friederichs

Reputation: 33563

You are writing info in a piece of unallocated memory. Use malloc to allocate some memory, then use strncat to make sure it isn't going out of range:

char* output;
output = (char *)malloc(100*sizeof(char));
output[0] = '\0';
strncat(output, someStrings[1], 100);

Then, when you are done with the output result, call free() to give the memory back to the system. Mind you, you are treading into complex matter here. Do not think of dynamic memory allocation lightly.

Consult the manpages for more information. Or this: http://en.wikipedia.org/wiki/C_dynamic_memory_allocation

Upvotes: 0

CCoder
CCoder

Reputation: 2335

You have not allocated memory for the output string. Do use malloc() to allocate memory and then try strcat.

Upvotes: 6

Related Questions