-3

Every time I attempt to insert a string into a binary tree in my program, I have to use strcpy and use the strcpy's destination for it to insert successfully. If I do not use strcpy and use just the source, it will crash the program.

Example:

char *originalstring;
originalstring = (char *)calloc(alloc + 1, sizeof(char));
originalstring = "Hello.";
insert(&root, originalstring); //into binary tree

Results in a crash.

char *newstring, *originalstring;

originalstring = (char *)calloc(alloc + 1, sizeof(char));
originalstring = "Hello.";

newstring = (char *)calloc(alloc + 1, sizeof(char));
strcpy(newstring, originalstring);

insert(&root, newstring);

Inserts it into the tree. My full program is of course significantly larger than this, but I really don't think it has anything to do with me being forced to use a strcpy to insert a string. This leads me to asking whether or not strcpy has special things.

Edit: I have also attempted to manually nullbyte the end of originalstring and that has failed.

Laefica
  • 489
  • 1
  • 5
  • 13
  • You are not showing us enough to know exactly, but if your code would be trying to write into a `"string literal"`, yes, this may crash your execution, and rightly so. – Jens Gustedt Oct 17 '15 at 10:45
  • @Jens Gustedt could you elaborate further please? Both `newstring` and `originalstring` are the exact same, are they not? – Laefica Oct 17 '15 at 10:47

2 Answers2

2

When you do this:

originalstring = (char *)calloc(alloc + 1, sizeof(char));
originalstring = "Hello.";

you are firstly allocating some storage for a string, which is fine, but then in the second line you are replacing the pointer to this storage with a pointer to a string literal. The original allocation has then been "lost" (resulting in a memory leak), and if you try to modify the contents of originalString you will get undefined behaviour, since you're now pointing at what is most likely read-only memory. You will also get undefined behaviour if you subsequently try to free this string (since it was not allocated via malloc).

So, bottom line: always use strcpy to copy strings - only ever use direct assignment (=) when manipulating pointers to strings.


Some additional notes on coding style:

so the above allocation should really just be written as:

originalstring = calloc(alloc + 1, 1);
Community
  • 1
  • 1
Paul R
  • 208,748
  • 37
  • 389
  • 560
1

Assigned the string literal "Hello." to the pointer originalstring causes the pointer to point to that string literal,abandoning the allocated memory.this leads to crash in case you attempt to free this pointer or modify the string literal.

machine_1
  • 4,266
  • 2
  • 21
  • 42