foo doesn't look very useful. Maybe source should be where you get "random" and the function just returns the result of strdup?
Code:
#include <stdio.h>
#include <string.h>
char* modifiable(const char* source)
{
return strdup(source);
}
int main(void)
{
char* s = modifiable("random");
printf("%s\n", s);
return 0;
}
Also, C might not free memory at the end of the program and strdup uses malloc. You should free the memory when you're done. And I don't think strdup is a standard function, but it's not hard to write.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* strDup(const char* source)
{
char* result = malloc(strlen(source) + 1);
if (result != NULL)
{
strcpy(result, source);
}
return result;
}
char* modifiable(const char* source)
{
return strDup(source);
}
int main(void)
{
char* s = modifiable("random");
printf("%s\n", s);
free(s);
return 0;
}
But since all you're doing is returning the result of strdup, why not just use it in the first place?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* strDup(const char* source)
{
char* result = malloc(strlen(source) + 1);
if (result != NULL)
{
strcpy(result, source);
}
return result;
}
int main(void)
{
char* s = strDup("random");
printf("%s\n", s);
free(s);
return 0;
}
I don't think I like strdup. It's too hard to remember to free the memory.