Hello to all.
Is this program licking memory?
Code:int main() { while(i<100) { ... printf("Example %s\n",function()); ... i++; } return 0; } char* function () { char* data; ... data = "memory"; .... return data; }
Thanks!
Hello to all.
Is this program licking memory?
Code:int main() { while(i<100) { ... printf("Example %s\n",function()); ... i++; } return 0; } char* function () { char* data; ... data = "memory"; .... return data; }
Thanks!
Last edited by guillermoh; 02-06-2008 at 10:40 AM.
No.
If it were to actually compile and run, it would only be using the program stack.
Mainframe assembler programmer by trade. C coder when I can.
isn't 100,000 out of bounds for an integer? thought it was 16,000, unless i'm the dinosaur;->
The code is flawed.
1) It never calls the function, instead it prints the actual function address which is not a string. You may very well get junk or a crash.
2) The function "function" returns a pointer to local data. I'm not sure if it might just return a proper string, but I wouldn't bet on it.
3) It should be const char*, not char*.
4) i is never defined.
Do I need to malloc()?2) The function "function" returns a pointer to local data. I'm not sure if it might just return a proper string, but I wouldn't bet on it.
you need to call function like
function()
All problems in computer science can be solved by another level of indirection,
except for the problem of too many layers of indirection.
– David J. Wheeler
Sorry. typing mistakeyou need to call function like
function()
Does this solve my problems?
Code:int main() { gchar *string; while(i<100) { ... string = function(); printf("Example %s\n",string); free (string); ... i++; } return 0; } char* function () { char* data = ""; ... data = concatenate(data,"memory"); .... return data; } char * concatenate (char* str1, char* str2) { char *result; if ( str2 != NULL ) { result = malloc(strlen(str1) + strlen(str2) + 1); if ( result != NULL ) { strcpy(result, str1); strcat(result, str2); } } return result; }
I'm trying to solve this:
1) It never calls the function, instead it prints the actual function address which is not a string. You may very well get junk or a crash.
2) The function "function" returns a pointer to local data. I'm not sure if it might just return a proper string, but I wouldn't bet on it.