-
Makes NO SENSE
I wrote this function.
Code:
char* GetExtension(char* cFile)
{
char* cExt = (char*)malloc(30);
int i,x,z;
for(i=0;i<strlen(cFile);i++){
if(cFile[i] == '.'){
for(x=i+1;x<strlen(cFile);x++){
cExt[z++] = cFile[x];
}
cExt[z++] = '\0';
z++;
}
}
return cExt;
}
I call it in main, it works fine.
Code:
char* pNoSense = GetExtension("***NOSENSE.txt");
printf("NO SENSE: %s\n",pNoSense);
free(pNoSense);
return 0;
I call it later again in my program and it doesn't seem to return any output. I started putting it in random places to see *** the problem is, and at some places it even crashes the damn thing. Help?
-
Re: Makes NO SENSE
hmm..
well it appears you are returning a pointer to a stack based (temporary variable)... you create cExt in the method then return the pointer.. but after exiting the method that stack based variable is deleted, so that pointer is pointing to garbage...
use the keyword "new" to create a heap based variable or pass by reference.