Reputation: 17
i am learning somethings that about the dynamic memory allocations in C programming languages. When i was trying to write a program that describe as below:
Write a function named duplicate that uses dynamic storage allocation to create a copy of a string. For example, the call
p = duplicate(str);
would allocate space for a string of the same length as str, copy the contents of str into the new string, and return a pointer to it. Have duplicate return a null pointer if the memory allocation fails.
This is the exercise 2 of chapter17 in the book "C Programming Language, A Modern Approaches(2nd ver.)".
In my first attempt, i write my code as below:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char *duplicate(char* str){
char* news=(char*)malloc((strlen(str)+1)*sizeof(char));
if(news==NULL){
printf("Error: malloc failed\n");
return NULL;
}
strcpy(news,str);
return news;
}
int main(){
char *str,*p;
str="Hello world";
p=duplicate(str);
puts(p);
return 0;
}
which run successfully. But when i modify my code to call free(str) as below:
int main(){
char *str,*p;
str="Hello world";
p=duplicate(str);
free(str);
puts(p);
return 0;
}
it failed without any output and return an adnormal value. In my book it doesn't mention anything about this problem but only giving some example about the free() function that use on the pointer that did not assign any value. I am curious that what's wrong with my code? If i want to use the free function, what is the proper way to use it and how can i free the pointer pointed to a memory that has assigned some value?
Upvotes: 0
Views: 570
Reputation: 22154
The instruction
str="Hello world";
assigns the constant string "Hello world" to str. It does not allocate the storage for the string with malloc
. So you must not call free
with str
as argument. Only pointers obtained with a malloc
may be passed to free
.
"Hello world" is a constant string stored in a special location of the program. You must not free it and modify it.
Upvotes: 5