Very simple test of calloc() and free() failing

Hi, I've just been introduced to dynamic memory allocation, so I've written a small test to test out how it works. Can anyone tell me why this doesn't work?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
  char *str = calloc(5,1);
  str = "dog";
  free(str);
  str = calloc(5,1);
  str = "cat";
  printf("%s\n", str);  

  return 0;
}


*** glibc detected *** lab2: free(): invalid pointer: 0x0000000000400668 ***


How do you free pointers with the intent to use them again later?
On line 7 you assign a new value to str. str = "dog" doe not copy "dog" to memory location str, it allocates a new string "dog" and makes str point at it. Use strcpy(str, "dog")
These help a lot:

http://www.cplusplus.com/reference/clibrary/cstdlib/calloc/

Hint: missing (char*) somewhere...
Topic archived. No new replies allowed.