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

int main()
{
    
    char *cp;
    
    cp = (char *)malloc(10 * sizeof(char));
    cp="kerem";
    //strcpy(cp, "kerem");
    printf("%s",cp);
    cp=(char *)realloc(cp,30 * sizeof(char));
    //strcpy(cp, "kerem demir Aziz Kerem Demir");
    cp= "kerem demir Aziz Kerem Demir";
    printf("%s",cp);
    //free(cp);
 
   return 0;
}

While using the strcpy function, I can copy the pointer string without any problems, but; When I do this using char * I get this error: realloc(): invalid pointer

kerem0101
  • 3
  • 3
  • yes because you put 29 characters in 20 character space. The next 9 character spaces belong to realloc and your code steals them anyway – user253751 Dec 14 '22 at 16:48
  • 4
    `cp = "kerem"`? You're not copying, you're just changing where that pointer points to. Your first allocation is thrown into the void, and leaks memory. You **cannot** `realloc()` on a pointer like that as `"kerem"` was never allocated in the first place. – tadman Dec 14 '22 at 16:49
  • 1
    Side note: [Do I cast the result of malloc?](https://stackoverflow.com/q/605845/12149471) – Andreas Wenzel Dec 14 '22 at 16:53

2 Answers2

3

There are a few problems in this code:

  • It seems you expect cp="kerem"; to be copying the data to the location pointed to by cp, while in fact it just makes cp to point to the location of the string literal "kerem"
  • Having in mind the first bullet, you are calling realloc on a pointer to string literal which is not allowed
  • Even if we ignore the first two, the new size of cp would be 20, which is not sufficient to store the value you try to copy (even assuming you use strcpy instead of =).
Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
1

The crucial problem is the line:

cp="kerem";

The string literals in C works more or less (*) like this:

static char _unnamed_[] = "kerem";
cp = _unnamed_;

Now the cp points to a memory that does not originate from a dynamic allocation via malloc/realloc and it cannot be an argument for realloc without invoking Undefined Behavior.

That is why strcpy is required because it copies the content of the memory to another memory pointed by cp. The value of the pointer cp does not change.

(*) string literals cannot be modified, moreover literal with the same content may share the storage.

tstanisl
  • 13,520
  • 2
  • 25
  • 40