0

i need to detect the problem in the next code, and the reason to that problem and how to fix it. for some reason when i tried to run it in visual the error is on the free.

 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
 #include <malloc.h>
 int main()
 {
  char str1[] = "abcde";
  char* str2 = (char*)malloc(strlen(str1));
  strcpy(str2, str1);
  puts(str1);
  puts(str2);
  free(str2);
  return 0;
 } 

3 Answers3

1

it should be

char* str2 = (char*)malloc(strlen(str1)+1);
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
1

strlen return the length of null terminated string excluding the null character '\0'. You need to allocate space for null character too.

char* str2 = malloc(strlen(str1) + 1); // Do not cast return value of malloc
haccks
  • 104,019
  • 25
  • 176
  • 264
  • but why does the free function needs the null terminator? – johnny doe Jan 25 '16 at 18:36
  • @johnnydoe; That's may be because of undefined behavior. – haccks Jan 25 '16 at 18:37
  • I'm guessing the `strcpy` is overwriting the info needed to keep track of the allocation. Actually, I'm guessing it's not *this* allocation that's getting corrupted, but info on the space that's after the allocation. Therefore, when the `free` executes, it's not able to figure out what to do. – John Sensebe Jan 25 '16 at 18:53
  • @JohnSensebe; May be the case. – haccks Jan 25 '16 at 18:54
1

The issue, as others have mentioned, is that you're not allocating enough space for the string you want to copy. strlen returns the number of characters in the string, however that number doesn't include the null byte at the end that terminates the string.

So when you call strcpy, you're writing one byte past the end of the allocated memory. Once you write past your memory bounds, that invokes undefined behavior. That means your program might appear to work, it might crash (sometimes right away, sometimes later), or it might cause data corruption that would be hard to detect.

In this particular situation, the extra byte you wrote probably corrupted data used by the implementation of free and/or malloc. But with some other compiler or OS, it might work fine.

So to avoid undefined behavior, be sure to allocate the required amount of space:

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

Also, don't cast the return value of malloc, as that may mask other errors in your code.

Community
  • 1
  • 1
dbush
  • 205,898
  • 23
  • 218
  • 273