strcpy 堆栈粉碎并分配了足够的内存

问题描述 投票:0回答:1

运行以下代码时出现堆栈粉碎错误:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_NAME 12
#define MAX_DIR 10

struct Node {
    char name[MAX_NAME];
    struct Node *subdirs[MAX_DIR];
};

int mkdir(struct Node* root, char* path) {

   
   char current_path[MAX_NAME+1];
   strcpy(current_path, path);

   char *next_path = strchr(current_path+1, '/');
   char *token;

   if (!next_path) {
       int i = 0;
       while(i < MAX_DIR && root->subdirs[i]) ++i;
       token = strtok(path, "/");
       root->subdirs[i] = malloc(sizeof(struct Node)); 
       strcpy(root->subdirs[i]->name, current_path+1);
       return 1;
   }

   token = strtok(path, "/");

   while( token != NULL) {

      for(int i = 0; i < MAX_DIR; i++) {
          if (root->subdirs[i] && !strcmp(root->subdirs[i]->name, token))
              return mkdir(root->subdirs[i], next_path);
      }

      token = strtok(NULL, "/");
   }

   printf("not found\n");

   return 0;


}


int main() {

    char input1[] = "/test";
    char input2[] = "/test/bar";
    char input3[] = "/lib/bar";
    char input4[] = "/foo";
    char input5[] = "/test/bar/foaa";

    struct Node *root = malloc(sizeof(struct Node));

    mkdir(root, input1);
    mkdir(root, input2);
    mkdir(root, input5);


    return 0;

}

代码尝试模仿mkdir命令,对于输入“/test/bar/foaa”,如果/test/和/test/bar/都存在,则会在/test/bar/下创建foaa。

问题与此行相关:

       strcpy(root->subdirs[i]->name, current_path+1);

将常数

MAX_NAME
增加到 15 可以解决堆栈粉碎问题。 然而,“foaa”只有 5 个字符(包括 .所以,理论上,strcpy 有足够的空间。

我的假设/代码有什么问题?

arrays c string char
1个回答
0
投票

您的 current_path 变量的宽度为 13 个字节。你输入的5串有多长?

© www.soinside.com 2019 - 2024. All rights reserved.