C 中的 malloc() 返回已填充的内存

发布于 2025-01-11 01:50:55 字数 4689 浏览 0 评论 0原文

char *string = (char *) malloc(sizeof(char) * sz);

在此之前的代码->void insert_word(word *root, char string1[], int linenumber) { int sz=strlen(string1)<=MAX_WORD_LENGTH?strlen(string1):MAX_WORD_LENGTH; 代码块 3 拥有整个上下文

有时,malloc() 在使用时会返回已填充的内存位置。

令我困扰的是,这不是随机的。 (该程序包括从文件中获取单词并将它们传递给该函数。对于同一个单词,函数行为(特别是 malloc() 的行为)是不同的。

对于输入 string1=0x7fffffffdf10 "lol" root=BST,sz 得到一个3 的值

malloc() 分配给 string 的值为 0x55555555c510 "\340\305UUUU" 为什么 malloc 没有指向空内存位置? (这不是随机行为,而是可预测且可重复的) 此外,由于某种原因,此循环运行无限长的时间

while(strcmp(string1,string)!=0)
    {
        free(string);
        string=NULL;
        string = (char *) malloc(sizeof(char) * sz);
        strncpy(string,string1,sz);
    }

更多相关代码

  1. #define MAX_WORD_LENGTH 20

  2. 结构体定义

    typedef 结构体linkedList
        {
            整数;
            结构体linkedList *下一个;
        }列表;
        typedef 结构体 word_with_count
        {
            字符*字符串;
            列表*行号;
            struct word_with_count *left;
            struct word_with_count *右;
        }词;```
    

函数

void insert_word(word *root, char string1[], int linenumber) {
    int sz=strlen(string1)<=MAX_WORD_LENGTH?strlen(string1):MAX_WORD_LENGTH;
    char *string = (char *) malloc(sizeof(char) * sz);
    strncpy(string,string1,sz);
    if (root==NULL) {
        return;
    } else if (strcmp(string, root->string) < 0) {
        if (root->left == NULL) {
            root->left = createword(string, linenumber);
        } else {
            insert_word(root->left, string, linenumber);
        }
    } else if (strcmp(string, root->string) > 0) {
        if (root->right == NULL) {
            root->right = createword(string, linenumber);
        } else {
            insert_word(root->right, string, linenumber);
        }
    } else {
        append_list(linenumber, root->linenumbers);
    }
    free(string);
}
  1. [3] )调用该函数的
int main() {
    char path[MAX_PATH_LENGTH];
    FILE *fp;
    fgets(path, MAX_PATH_LENGTH, stdin);

    if (strlen(path) > 0 && path[strlen(path) - 1] == '\n')
        path[strlen(path) - 1] = '\0';
    
    fp = fopen(path, "r");
    if (fp == NULL) {
        printf("File not found\n");
        return 0;
    }
    char ch;
    int line_count = 1;
    char current_word[MAX_WORD_LENGTH] = "";

    word *root = NULL;
    while (!feof(fp)) {
        ch = fgetc(fp);
        //printf("%c", ch);

        if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') {
            if (ch >= 'A' && ch <= 'Z')
                ch = ch - 'A' + 'a';

            strncat(current_word, &ch, 1);
        } else if (ch == '-') {
            continue;
        } else {
            if (strlen(current_word) > 2) {
                if (root == NULL) {
                    root = createword(current_word, line_count);
                } else {
                    insert_word(root, current_word, line_count);
                }
            }
            memset(current_word, 0, sizeof(current_word));
            if (ch == '\n') {
                line_count++;
            }
        }
    }
    if (strlen(current_word) > 2) {
        if (root == NULL) {
            root = createword(current_word, line_count);
        } else {
            insert_word(root, current_word, line_count);
        }
    }
    fclose(fp);
    // print_tree(root);
    //printf("\n");
    //print_tree(root);
    int status=delete_low_ocurrence(root, NULL, 3);
    if (status == -1)root = NULL;
    print_tree(root);
    freetree(root);
    return 0;
}

main() 5) 该函数使用的辅助函数

word* createword(char string[], int linenumber)
{
    word *newword = (word*)malloc(sizeof(word));
    int sz=strlen(string)<=MAX_WORD_LENGTH?strlen(string):MAX_WORD_LENGTH;
    newword->string = (char*)malloc(sizeof(char)*sz);
    strncpy(newword->string, string,sz);
    newword->linenumbers = (list*)malloc(sizeof(list));
    newword->linenumbers->number = linenumber;
    newword->linenumbers->next = NULL;
    newword->left = NULL;
    newword->right = NULL;
    return newword;
}
  1. 作为输入给出的文本文件
much2f
much3f
lol
lol
lol
qwertyuiopasdfghjklzxcvbnmqwertyuiop
qwertyuiopasdfghjklzxcvbnmqwertyuiop
qwertyuiopasdfghjklzxcvbnmqwertyuiop
qwertyuiopasdfghjklzxcvbnmqwertyuiop

char *string = (char *) malloc(sizeof(char) * sz);

code right before this->void insert_word(word *root, char string1[], int linenumber) { int sz=strlen(string1)<=MAX_WORD_LENGTH?strlen(string1):MAX_WORD_LENGTH; Code block 3 has the entire context

Sometimes malloc() returns a populated memory location while using it.

What bothers me is that this is not random.
(This program consists of taking words from a file and passing them to this function. For THE SAME WORD, the function behaviour(in particular that of malloc()) is different.

For the inputs
string1=0x7fffffffdf10 "lol" root=BST, sz gets a value of 3

The value allocated to string by malloc() is 0x55555555c510 "\340\305UUUU" Why is malloc not pointing to an empty memory location? (This is not random behaviour, it is predictable and repeatable)
Furthermore,this loop runs an infinite amount of time for some reason

while(strcmp(string1,string)!=0)
    {
        free(string);
        string=NULL;
        string = (char *) malloc(sizeof(char) * sz);
        strncpy(string,string1,sz);
    }

MORE RELAVANT CODE

  1. #define MAX_WORD_LENGTH 20

  2. Definition of the structures

    typedef struct linkedList
        {
            int number;
            struct linkedList *next;
        }list;
        typedef struct word_with_count
        {
            char* string;
            list *linenumbers;
            struct word_with_count *left;
            struct word_with_count *right;
        }word;```
    

[3] ) The function

void insert_word(word *root, char string1[], int linenumber) {
    int sz=strlen(string1)<=MAX_WORD_LENGTH?strlen(string1):MAX_WORD_LENGTH;
    char *string = (char *) malloc(sizeof(char) * sz);
    strncpy(string,string1,sz);
    if (root==NULL) {
        return;
    } else if (strcmp(string, root->string) < 0) {
        if (root->left == NULL) {
            root->left = createword(string, linenumber);
        } else {
            insert_word(root->left, string, linenumber);
        }
    } else if (strcmp(string, root->string) > 0) {
        if (root->right == NULL) {
            root->right = createword(string, linenumber);
        } else {
            insert_word(root->right, string, linenumber);
        }
    } else {
        append_list(linenumber, root->linenumbers);
    }
    free(string);
}
  1. main() which calls this function
int main() {
    char path[MAX_PATH_LENGTH];
    FILE *fp;
    fgets(path, MAX_PATH_LENGTH, stdin);

    if (strlen(path) > 0 && path[strlen(path) - 1] == '\n')
        path[strlen(path) - 1] = '\0';
    
    fp = fopen(path, "r");
    if (fp == NULL) {
        printf("File not found\n");
        return 0;
    }
    char ch;
    int line_count = 1;
    char current_word[MAX_WORD_LENGTH] = "";

    word *root = NULL;
    while (!feof(fp)) {
        ch = fgetc(fp);
        //printf("%c", ch);

        if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') {
            if (ch >= 'A' && ch <= 'Z')
                ch = ch - 'A' + 'a';

            strncat(current_word, &ch, 1);
        } else if (ch == '-') {
            continue;
        } else {
            if (strlen(current_word) > 2) {
                if (root == NULL) {
                    root = createword(current_word, line_count);
                } else {
                    insert_word(root, current_word, line_count);
                }
            }
            memset(current_word, 0, sizeof(current_word));
            if (ch == '\n') {
                line_count++;
            }
        }
    }
    if (strlen(current_word) > 2) {
        if (root == NULL) {
            root = createword(current_word, line_count);
        } else {
            insert_word(root, current_word, line_count);
        }
    }
    fclose(fp);
    // print_tree(root);
    //printf("\n");
    //print_tree(root);
    int status=delete_low_ocurrence(root, NULL, 3);
    if (status == -1)root = NULL;
    print_tree(root);
    freetree(root);
    return 0;
}

5)Auxilary function used by this function

word* createword(char string[], int linenumber)
{
    word *newword = (word*)malloc(sizeof(word));
    int sz=strlen(string)<=MAX_WORD_LENGTH?strlen(string):MAX_WORD_LENGTH;
    newword->string = (char*)malloc(sizeof(char)*sz);
    strncpy(newword->string, string,sz);
    newword->linenumbers = (list*)malloc(sizeof(list));
    newword->linenumbers->number = linenumber;
    newword->linenumbers->next = NULL;
    newword->left = NULL;
    newword->right = NULL;
    return newword;
}
  1. Textfile given as input
much2f
much3f
lol
lol
lol
qwertyuiopasdfghjklzxcvbnmqwertyuiop
qwertyuiopasdfghjklzxcvbnmqwertyuiop
qwertyuiopasdfghjklzxcvbnmqwertyuiop
qwertyuiopasdfghjklzxcvbnmqwertyuiop

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

忆梦 2025-01-18 01:50:55

为什么 malloc 没有指向空的内存位置?

因为它可以。未指定通过malloc()分配的内存的内容。

如果代码需要将内存清零,请参阅calloc()


错误代码

strncpy(string,string1,sz) 不会导致 string 成为字符串,因为它可能缺少空字符终止。下面的 (strcmp(string...) 是未定义行为。相反,不要使用 strncpy(),而是使用 strcpy( ) 并确保先前的分配有足够的空间容纳终止空字符

strncpy(string,string1,sz);
...
} else if (strcmp(string, root->string) < 0) { // bad

修复代码

word* createword(const char string[], int linenumber) {
  word *newword = calloc(1, sizeof *newword);
  size_t length = strlen(string);
  if (length > MAX_WORD_LENGTH) {
    length = MAX_WORD_LENGTH;
  }
  char *s = malloc(length + 1); // Include room for the \0
  list *linenumbers = calloc(1, sizeof *linenumbers);
  // Test allocation success
  if (newword == NULL || s == NULL || linenumbers == NULL) {
    free(newword);
    free(s);
    free(linenumbers);
    return NULL;
  }
  memcpy(s, string, length);  // Only copy the first 'length' characters.
  s[length] = 0;
  newword->string = s;
  newword->linenumbers = linenumbers;
  newword->linenumbers->number = linenumber;
  newword->linenumbers->next = NULL;
  newword->left = NULL;
  newword->right = NULL;
  return newword;
}

为什么是“while (!feof (file) )”总是错误?

feof(fp) 此处使用不当,fgetc() 返回 257 个不同的值。不要使用char ch

//char ch;
//...
//while (!feof(fp)) {
//    ch = fgetc(fp);

int ch;
...
while ((ch = fgetc(fp)) != EOF) {;

Why is malloc not pointing to an empty memory location?

Because it can. The content of the allocated memory via malloc() is not specified.

If code needs zeroed out memory, see calloc().


Bad code

strncpy(string,string1,sz) does not result in string being a string as it may lack null character termination. The following (strcmp(string... is then undefined behavior. Instead, do not use strncpy(), use strcpy() and make certain the prior allocation has enough room for the terminating null character.

strncpy(string,string1,sz);
...
} else if (strcmp(string, root->string) < 0) { // bad

Repaired code

word* createword(const char string[], int linenumber) {
  word *newword = calloc(1, sizeof *newword);
  size_t length = strlen(string);
  if (length > MAX_WORD_LENGTH) {
    length = MAX_WORD_LENGTH;
  }
  char *s = malloc(length + 1); // Include room for the \0
  list *linenumbers = calloc(1, sizeof *linenumbers);
  // Test allocation success
  if (newword == NULL || s == NULL || linenumbers == NULL) {
    free(newword);
    free(s);
    free(linenumbers);
    return NULL;
  }
  memcpy(s, string, length);  // Only copy the first 'length' characters.
  s[length] = 0;
  newword->string = s;
  newword->linenumbers = linenumbers;
  newword->linenumbers->number = linenumber;
  newword->linenumbers->next = NULL;
  newword->left = NULL;
  newword->right = NULL;
  return newword;
}

Why is “while ( !feof (file) )” always wrong?

feof(fp) improperly used here. fgetc() returns 257 different values. Do not use char ch.

//char ch;
//...
//while (!feof(fp)) {
//    ch = fgetc(fp);

int ch;
...
while ((ch = fgetc(fp)) != EOF) {;
扬花落满肩 2025-01-18 01:50:55

这是很正常的行为。 “malloc”只是进行内存分配,它不会对该内存位置中已有的内容做出任何承诺。您可能需要的是“calloc”,它会清除内存然后将其分配给您的程序。

This is quite normal behaviour. 'malloc' just does the memory allocation, it makes no commitment on what's already in that memory location. What you probably need is 'calloc', which clears the memory and then allocates it to your program.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文