1

All I want to ask a question that if we have two string but these should be in the given code

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

char *getln()
{
    char *line = NULL, *tmp = NULL;
    size_t size = 0, index = 0;
    int ch = EOF;

    while (ch) {
        ch = getc(stdin);
        if (ch == EOF || ch == '\n')
            ch = 0;
        if (size <= index) {
            size += index;
            tmp = realloc(line, size);
            if (!tmp) {
                free(line);
                line = NULL;
                break;
            }
            line = tmp;
        }
        line[index++] = ch;
    }

    return line;
}
char * combine(char *a,char *buffer){
   int stop_var;
   int newSize = strlen(a)  + strlen(buffer) + 1; 
   char * newBuffer = (char *)malloc(newSize);
   strcpy(newBuffer,a);
   strcat(newBuffer,buffer); // or strncat
   //printf("Final String %s",newBuffer);
   free(a);
   a = newBuffer;
   return newBuffer;
}
char * fun(char *str)
{
    char *str1;
    str1=getln();
    str=combine(str,str1);
    return str;
}
int main(void)
{
    char *str;
    str= getln();
    printf("Initial String %s \n",str);
    str=fun(str);
    printf("Final String %s \n",str);
}

this code is working fine but string char *str="Fixed value" is fixed is gives runtime error

int main(void)
{
    char *str;
    str= "Fixed Value";
    printf("Initial String %s \n",str);
    str=fun(str);
    printf("Final String %s \n",str);
} 

So, I want to know is it any other way to run the above case in which the string is fixed. I know that "How can we achieve the final value in the same character pointer".

Please Read Note: There are many Questions related to this question I have tried all the solutions. I looked the below solutions

  1. concatenate-two-char-arrays-into-single-char-array-using-pointers

  2. concatenate-two-char-arrays

  3. how-to-concatenate-pointer-arrays

  4. concatenate-char-array-in-c

  5. concatenate-two-arrays-using-void-pointer-c

I have searched many more solutions over the internet, but no solutions are fulfilled my condition. These all the solution is using the third variable and showing its value. I want value in the same variable. Even if we are creating any extra variable, its value finally should be assign to char *str.

Please provide me any suggestion to do this in c language only.

The given question is different from my question because in that question they checking the behaviour of the string literals bu for my case I am looking to assigns concatenate value to variable str. And its solution changing pointer to an array but I cannot change because its value is using many functions for my work.

Community
  • 1
  • 1
  • What's wrong with `strcat()` actually? – πάντα ῥεῖ Oct 12 '15 at 18:33
  • @NathanOliver Why is this a duplicate? This is not directly related to modifying string literals (only indirectly, through `free()`). – fuz Oct 12 '15 at 18:35
  • and you already use realloc extensively, so why all the magic in combine? Just get your input strings, realloc the first to be large enough to fit both, and then strcat into that... – Marcus Müller Oct 12 '15 at 18:35
  • In case also if I removed the 'free()' from the combine function then the code is throwing segmentation fault. If any other way directly or indirectly to modify the literal then suggest me please. – Krishnasai Gudavalli Oct 12 '15 at 18:59
  • @KrishnasaiGudavalli You cannot modify string literals. There is no way to do that. You can create an array and initialize it with a string literal if you want something writeable. – fuz Oct 12 '15 at 19:00
  • @FUZxxl Can you Explain the reason why I can not make any change to string literal? Please If you have related document then share that document with all of us. – Krishnasai Gudavalli Oct 12 '15 at 19:08
  • @KrishnasaiGudavalli Because the C standard says so (cf. ISO 9899:2011 §6.8.5 ¶7). – fuz Oct 12 '15 at 21:30

2 Answers2

2

Your function combine() calls free() on its first argument. In your fun() call, which is passed from fun() which points to a string literal in your code.

You cannot call free() on a string literal, that's undefined behaviour. I suggest you to restructure your code so that combine() no longer calls free() on its first argument. Freeing memory should be the callers responsibility.

fuz
  • 88,405
  • 25
  • 200
  • 352
0

I would suggest pairs of allocation/deallocation functions:

char * combine_allocate(const char *a, const char *b) {
    char* result = malloc(...)
    combine ...
    return result;
}

void combine_deallocate(char* p) { free(p); }

Having that:

char* a = initial_allocate();
char* b = initial_allocate();
char* c = combine_allocate(a, b);
initial_deallocate(a);
initial_deallocate(b);
// ... use c
combine_deallocate(c)

You may omit (and should) initial_allocate/initial_deallocate for string literals. It might be a bit too verbose, but object oriented C does nothing else (with nicer function names).

  • This one is not the generic solution because it is the compiler dependent so it will not work for older compiler versions. – Krishnasai Gudavalli Oct 12 '15 at 19:02
  • @KrishnasaiGudavalli This is old fashioned, too. –  Oct 12 '15 at 19:09
  • Please send me the working code which can fulfill my case to change the string literal. – Krishnasai Gudavalli Oct 12 '15 at 19:12
  • 1
    @KrishnasaiGudavalli - No –  Oct 12 '15 at 19:13
  • @KrishnasaiGudavalli Write your own code. Stack Overflow is **not** a code writing service. Asking “can you send me code” is the easiest way to get your questions closed. – fuz Oct 12 '15 at 21:31
  • @FUZxxl Sorry for asking the code but I want to know about the initial_allocate() function which can work for all platform of C in which header file it is available ? Is it user defined function that I have to create or it contains by some standard library? – Krishnasai Gudavalli Oct 13 '15 at 03:48
  • `int main() { char *a=initial_allocate(); char *a="sds"; printf("%s",a); }` This code is not working as I said the `char *a` is always have this initialization and I can not change it because If I chage it then the program will throw lots of error where ` *a ` is used – Krishnasai Gudavalli Oct 13 '15 at 04:02
  • @KrishnasaiGudavalli “initial_allocate()` is not meant as a concrete function but is rather just a placeholder for your own allocation function. Do you know of the `strdup()` function? It might solve your problem. – fuz Oct 13 '15 at 06:39