0

I want to allocate memory in an existing and still want to save the stored data inside of that string

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

main()
{
char *str1= "hello";
char *str2= "Abhimanyu";

char *str = malloc( strlen(str1) + strlen(str2) +1 );

strcpy(str,str1);
strcat(str,str2);
printf("%s",str);
return 0;
}

what i want is that i allocate some using malloc in the existing str1 and not using str is it possible?

5 Answers5

1

what i want is that i allocate some using malloc in the existing str1 and not using str is it possible?

You can certainly point str1 to some other memory if you no longer need it to point to the string literal.
Just assign the new value.
The function for reallocating is realloc.

Some facts you might need:

  • A string literal may not be changed, even though it has type char[] it is actually constant.
    It is allocated statically, so has nothing to do with mallocand such.
    All constant literals, including string literals, can potentially share storage.
  • There's a POSIX function for duplicating a string (memory internally allocated with malloc): strdup()
  • You can realloc memory allocated with compatible functions on the heap. That includes: malloc calloc realloc (strdup). Don't forget free.
  • If you reallocate memory, unless the reallocation fails (returns NULL), you may not use the old pointer any longer. All data was copied from the old to the new memory block, up to the minimum of old and new length. The rest is uninitialized.

Aside: Be aware that main nearly always has a return type of int, and implicit return types are ancient legacy.
If you use a decent compiler, asking for all warnings -Wall -Wextra -pedantic and selecting a modern standard (C99 or C11) will help you.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • Regarding _that main always has a return type of int_ Caution when using _always_ or _never_. The C99 standard does allow for other implementation-defined signatures, and you can use these if you've read the manual for your compiler and it says you can. ***(5.1.2.2.1) It shall be defined with a return type of int and with no parameters ... or with two parameters ... or in some other implementation-defined manner*** ( ***[from this post](http://stackoverflow.com/a/9356660/645128)*** ) – ryyker Jul 21 '14 at 23:11
  • I am only a little disappointed that you are not offering an alternative point of view. I'm not really up for a good strong debate on the topic, as I am not even pedantic about that rule, I just notice _always_ and _never_ rarely apply. Ever. – ryyker Jul 21 '14 at 23:28
1

The only approach that I see is the following

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

#define HELLO "hello"

int main( void )
{
   char *str2 = "Abhimanyu";
   char *str1 = malloc( sizeof( HELLO ) );

   strcpy( str1, HELLO );

   str1 = realloc( str1, strlen( str1 ) + strlen( str2 ) +1 );
   strcat( str1, str2 );

   printf( "%s\n", str1 );

   free( str1 );

   return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • don't forget to check if `malloc`/`realloc` failed. – twain249 Jul 21 '14 at 23:22
  • @VladfromMoscow should it be like this //////// str1 = (char *) relloc(str1 , new_size) ? –  Jul 22 '14 at 00:11
  • @Noobsplzdon't There is no necessity to specify the casting in C thogh for the documentation purpose it is useful to specify it. – Vlad from Moscow Jul 22 '14 at 11:08
  • @Noobsplzdon't-1 you shouldn't cast the result of `malloc` in C http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – twain249 Jul 23 '14 at 00:06
0

You can use realloc to increase the memory block pointed to by a pointer but the realloc implementation may end up moving your data to a different location in memory and changing the pointer's address so you should always double check your pointer. This can happen if the requested new size is larger than what's available.

If there's a really good reason why you need to be able to dynamically resize a memory block pointed to by a pointer then you probably need to think about building your own memory allocator or buffer pool and take ownership of managing the memory in the pool.

Mike Dinescu
  • 54,171
  • 16
  • 118
  • 151
0

You can use realloc to try to resize a previous allocation. It does not work on arbitrary pointers, such as your str1 = "hello"† – you need to allocate the initial area with, e.g., malloc. It may also end up allocating a new area at a different address (and copying the contents of the old area there), i.e., you must update all pointers that refer to the old area to point to the new area returned by realloc.

If these constraints are not acceptable, you are out of luck and need to design your program in some other way (e.g., set a maximum length and reserve that much space to begin with, then just use as much as you need).

† Also note that string literals, such as "hello", are not modifiable to begin with. The typical way around this is to use an array instead, e.g., char str1[] = "hello", but that can't be resized either. (But you could specify a larger size for it than needed for its initial contents if you know you will be storing a longer string there later.)

Arkku
  • 41,011
  • 10
  • 62
  • 84
0

I believe you are asking whether you can take this declaration:

char * str1 = "hello";

and somehow cause there to be some extra space available pointed to by str1.

The answer is don't do this! Notice that str1 is a local (stack) variable. It probably points to some literal pool, but it may point to more space allocated on the stack.

So doing this sort of thing

char * str1 = hello;
...
str1 = realloc (str1, 100);

may give rise to dom! (a UNIX sixth edition joke appropriate to the OP's style of coding).

O. Jones
  • 103,626
  • 17
  • 118
  • 172
  • It has to point to something with static storage duration (up to the as-if rule, of course); e.g. if this function returned `str1` then the pointer has to remain valid. – M.M Jul 21 '14 at 22:48