开发者

C char pointer problem weird values concatonated toward the end

Hi I am having trouble with this function. For some reason weird values are appended to the string at random times.

/* ex: path = /usr/src/data returns: /usr/src */``
char* get_pathname(char* path) {
  char* pathname;
  char* temp;
  int file开发者_如何学编程namelength;
  int pathlength;
  temp = get_filename(path); //name of file within original path
  filenamelength = strlen(temp);
  printf("strlen(temp) %d\n", strlen(temp));
  printf("strlen(path) %d\n", strlen(path));
  pathlength = strlen(path);
  pathname = malloc((pathlength-filenamelength-1));
  strncpy(pathname, path, pathlength-filenamelength-1);

  return pathname;
}

/* ex: path /usr/src/data returns: data */
char* get_filename(char* path) {
  char* get_filename(char* path){
  char* filename;
  char* temp = strrchr(path, '/')+1; //name of file within original path
  filename = malloc(sizeof(char) * (strlen(path) + 1));
  strcpy(filename, temp);
  return filename;
}


strncpy doesn't 0-terminate when the copied string is larger than or exactly fits the passed size.

pathname = malloc((pathlength-filenamelength-1));
strncpy(pathname, path, pathlength-filenamelength-1);

Change to:

pathname = malloc(pathlength-filenamelength);
                                          ^^^
strncpy(pathname, path, pathlength-filenamelength-1);
pathname[pathlength-filenamelength-1] = 0;


static void *
xmalloc(size_t n)
{
  void *obj = malloc(n);
  if (obj == NULL) {
    perror("xmalloc");
    exit(EXIT_FAILURE);
  }
  return obj;
}

char *
get_pathname(const char *path)
{
  char *slash = strrchr('/', path);
  if (slash == NULL) {
    char *dot = xmalloc(2);
    strcpy(dot, ".");
    return dot;
  }
  char *parent = xmalloc((slash - path) + 1);
  memcpy(parent, path, slash - path);
  parent[slash - path] = '\0';
  return parent;
}

char *
get_filename(const char *path)
{
  const char *slash = strrchr('/', path);
  const char *filename = (slash == NULL) ? "" : (slash + 1);
  char *result = xmalloc(strlen(filename) + 1);
  strcpy(result, filename);
  return result;
}

I've added the missing error handling and the cases when there is no slash in the given path. In your original code you had a memory leak in get_pathname: you called malloc via get_filename, but didn't free this memory after you used it.


Will this work for you?

char *get_path(char *path)
{
    char *fpath = NULL;
    char *slash = NULL;
    if(path == NULL) goto error;
    fpath = strdup(path);
    if(fpath == NULL) goto error; 
    slash = strrchr(fpath, '/');
    if(slash != NULL) *slash = '\0';
error:
    return fpath;

}

char *get_filename(char *path)
{
    char *slash = NULL;
    char *fname = NULL;
    if(path == NULL) goto error;
    slash = strrchr(path, '/');
    fname = (slash != NULL) ? strdup(slash + 1) : NULL;
error:
    return fname;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜