C char指针问题怪异的值朝着末尾连接起来

时间:2011-04-23 20:45:22

标签: c string pointers

嗨我这个功能有问题。由于某些原因,奇怪的值会随机附加到字符串中。

/* ex: path = /usr/src/data returns: /usr/src */``
char* get_pathname(char* path) {
  char* pathname;
  char* temp;
  int filenamelength;
  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;
}

3 个答案:

答案 0 :(得分:4)

当复制的字符串大于或完全符合传递的大小时,

strncpy不会终止。

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

更改为:

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

答案 1 :(得分:1)

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;
}

我添加了缺少的错误处理以及给定路径中没有斜杠的情况。在原始代码中,您get_pathname内存泄漏:您通过malloc呼叫get_filename,但在使用后没有free此内存。

答案 2 :(得分:1)

这对你有用吗?

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;
}