首页 文章

动态内存分配代码

提问于
浏览
1

我正在学习C(C)中的内存分配基础知识 .

#include "stdio.h"
#include "string.h"
#include "stdlib.h"
void main(){

    char *str;
    char *input;
    int *ilist;
    int i, size1, size2;

    printf("Number of letters in word: ");
    scanf("%d", &size1);
    printf("Number of integers: ");
    scanf("%d", &size2);                  

    str = (char *)malloc(size1*sizeof(char) + 1); 

    ilist = (int *)malloc(size2*sizeof(int)); 
    if (str == NULL || ilist == NULL){ 
        printf("Lack of memory");
    }
    printf("Word: ");
    int k = size1;
    // the following line is done to prevent memory bugs when the amount of 
    letters in greater than size1.
    scanf("%ks", &str); //I guess something is wrong with this line
    /* user inputs a string */
    for (i = 0; i < size2; i++) {
        printf("Number %d of %d: ", i + 1, size2);
        //this scanf is skipped during the execution of the program
        scanf("%d", ilist + i);         
    }


    free(str);
    free(ilist);
    system("pause");

}

程序要求用户写入单词中的字母数量和数字中的位数 . 然后用户写下这个词 . 然后他逐个写整数,具体取决于之前键入的数字 . 我遇到的问题是当用户写完整个单词时,跳过下一个scanf . 谢谢 . 附:在这段代码中可以有其他类型的内存错误吗?

2 回答

  • 2

    关于//我猜这条线有问题......
    scanf("%ks", &str); 中的格式说明符 "%ks" 包含k,它不是有效的scanf() format specifier .

    链接摘录:

    enter image description here

    对于 width 说明符中的用户输入值,您可以创建格式缓冲区:

    char format[10];
    int k = size1;//assume size1 == 10
    sprintf(format, "%c%d%c", '%', k, 's');
    //assuming k == 10, format contains "%10s"
    scanf(format, &str); //now, there is nothing wrong with this line
    

    其他观察
    several recommended prototypes for the C main function . void main() 不是其中之一 .

    This linestr = (char *)malloc(size1*sizeof(char) + 1);
    可以写成:

    str = malloc(size1 + 1); //removed sizeof(char) as it is always 1
                             //removed cast, not recommended in C
    

    Similar for for: ilist = (int *)malloc(size2*sizeof(int));

    ilist = malloc(size2*sizeof(int));//remove cast, but keep sizeof(int) 
                                      //unlike sizeof(char), sizeof(int) is never 1
    

    C中动态内存分配需要考虑的一些基础知识:

    1)在C中,不要转换calloc(), malloc() or realloc()的输出 . (但是用C表示 . )
    2)每次调用calloc(),malloc()或realloc()时,都必须有相应的free()调用
    3)虽然自动内存源自stack,但动态内存来自heap
    4)如果是speed efficiency is important,则优先于堆栈上的堆栈 .

  • 1

    而不是使用 scanf 使用fgets . 但是,您需要首先清除输入缓冲区以消耗之前 scanf 留下的 \n .

    int c;
    while((c = getchar()) != '\n' && c != EOF); // Clear input buffer  
    fgets(str, k, stdin);
    

    请注意,如果读取 '\n' ,则它将存储在 str 中 . 你应该照顾好这一点 .

相关问题