Hai,
I've tried to write a function that takes a string and allocates a sufficent amount of memory and the copies the string there.
But i have run into a minor dilemma.
My code looks like this:
When the call to the function have finished you're supposed to clean up after yourself by calling free(), but p is local to the function and can't be reached from outside. And calling free() just after return defeats the purpose by revoking the allocated memory.
But then, maybe this is the wrong way to do this kind of thing?
Minor side question: How does the compiler know that *sizeof(char) does not refer to a pointer, but a multiplication?
I've tried to write a function that takes a string and allocates a sufficent amount of memory and the copies the string there.
But i have run into a minor dilemma.
My code looks like this:
Code:
char *stringcopy(char *str){
int len = strlen(str);
char *p = (char *)malloc(len *sizeof(char));
char *ptr = &p[0];
while((*p++ = *str++) != '\0');
return ptr;
}
When the call to the function have finished you're supposed to clean up after yourself by calling free(), but p is local to the function and can't be reached from outside. And calling free() just after return defeats the purpose by revoking the allocated memory.
But then, maybe this is the wrong way to do this kind of thing?
Minor side question: How does the compiler know that *sizeof(char) does not refer to a pointer, but a multiplication?