Reputation: 1579
I'm writing a function that removes the last segment of the path to a file, but I'm not getting the right string back from my function. I give the function the input sample/four.txt/one.txt"
as a sample parameter, and I want to get sample/four.txt
back. I've tried the code on my own machine, and getOldPath
always returns sample/f
. Inside the getOldPath
function, curPath
is sample/four.txt
. Once I exit and assign it to newPath
in the main, newPath
is sample/f
. However, when I run the program on my friend's machine, he gets the expected sample/four.txt
. What is causing this issue and how can I fix it? Here is the code that I am working with:
#include <stdio.h>
#include <string.h>
char *getOldPath(char *curPath)
{
// Loop to find the count of characters
int count;
count = 0;
int end;
end = strlen(curPath);
char tempChar;
tempChar = curPath[end-1];
while(tempChar != '/')
{
count++;
end--;
printf("End is: %i\n",end);
tempChar = curPath[end];
}
char temp[256];
int numChar;
numChar = strlen(curPath) - count;
strncpy(temp,curPath,numChar);
curPath = temp;
printf("The path is: %s\n",curPath);
return curPath;
}
int main(int argc, char **argv)
{
char *path = "sample/four.txt/one.txt";
char *newPath = getOldPath(path);
printf("Do we get the new path back: %s\n",newPath);
}
Upvotes: 2
Views: 275
Reputation: 344
You are returning the temp
address which is a local variable in the function so it will not work. Modified your function to contain the truncated path in the input string and also used the strrchr()
function. Check — it might be useful to you.
void getOldPath(char *curPath)
{
char *ptr;
ptr = strrchr(curPath,'/');
if(ptr != NULL)
{
*ptr = '\0';
}
printf("The path is: %s\n",curPath);
}
Upvotes: 1
Reputation: 182619
You are returning a pointer to an object - temp
- that has automatic storage duration. What this means is that temp
only exists during the lifetime of the invocation of that function. Using it after the function has returned is undefined behavior and will produce erratic results.
If you want it to persist beyond the end of the function, you can use malloc
or refactor your code altogether to use caller-provided memory. For example, a drop-in replacement could be:
char *temp = malloc(256);
/* The caller must remember to free this. */
Upvotes: 3