如何在C中正确使用malloc ?

时间:2022-09-06 16:49:44

I'm trying to allocate some memory using malloc (I don't have much experience with malloc as I am just starting to learn how to use it), and I am getting a warning before compiling with my IDE.

我尝试使用malloc(我没有太多的malloc经验)来分配内存(我刚开始学习如何使用malloc),在使用IDE编译之前,我得到了一个警告。

int numInSeq = 0;
int i;

printf("How many numbers do you have in your sequence: ");
scanf("%d", &numInSeq);

double* sequence = (double*) malloc(numInSeq * sizeof(double));

printf("Enter the sequence of the numbers you have (seperated by spaces): ");
for (i = 0; i < numInSeq; i++) {
    scanf("%lf", &sequence[i]);
}

The warning is on the line where I call malloc, and it says: Implicitly declaring library function 'malloc' with type 'void *(unsigned long)'

警告是在我调用malloc的地方,它说:隐式声明库函数'malloc'和类型'void *(unsigned long)'

Is this in incorrect way of formatting that line of code? The program still compiles, but there are some unexpected results that I get when testing.

这是用不正确的方式格式化这行代码吗?这个程序仍然在编译,但是我在测试时得到了一些意想不到的结果。

4 个解决方案

#1


3  

Use <stdlib.h> or <cstdlib> as suggested by Scott, also, always make sure malloc return valid pointer by NULL check.

使用< stdlib。根据Scott建议的h>或 ,也要确保malloc返回有效指针为空检查。

//malloc unable to allocate memory
if(sequence == NULL)
{
//return;
}

At the end, use free to freeup memory and to avoid memory leak.

最后,使用空闲内存,以避免内存泄漏。

free(sequence);

#2


5  

Make sure to include <stdlib.h>.

确保包括

#3


2  

Important points while using malloc :

使用malloc时的要点:

  1. Malloc function call returns you the void pointer which points to the memory location , So you should cast it to your desired data type pointer explicitly.

    Malloc函数调用返回指向内存位置的空指针,因此您应该显式地将其转换为所需的数据类型指针。

  2. You should always remember to free the memory which you dynamically allocated using malloc. (very imp)

    您应该始终记得释放使用malloc动态分配的内存。(imp)

  3. You should always check if malloc function call was successful or not.

    您应该经常检查malloc函数调用是否成功。

FYI check this link: http://www.cplusplus.com/reference/cstdlib/malloc/

FYI检查这个链接:http://www.cplusplus.com/reference/cstdlib/malloc/。

Hope this helps.

希望这个有帮助。

#4


2  

How to use malloc correctly in C?

如何在C中正确使用malloc ?

  1. Be sure to include the correct header file. That fixes OP's compiler warning.

    确保包含正确的头文件。修正了OP的编译器警告。

    #include <stdlib.h>
    
  2. Casting the return is allowed but frowned upon in C as being unnecessary. Other may disagree, so best to follow your group's coding standard.

    在C语言中,选择return是允许的,但在C中是不允许的。其他的可能不同意,所以最好遵循你的团队的编码标准。

    double* sequence = /* cast not required */ malloc(...);
    
  3. Consider the follow style as it is easier to code, review, maintain and IMO, less error prone.

    考虑下面的样式,因为它更容易编码、检查、维护和IMO,更容易出错。

    // object_pointer = malloc(sizeof *object_pointer * num_elements);
    // Example
    double* sequence = malloc(sizeof *sequence * numInSeq);
    
  4. Remember the argument type is size_t and may differ in size than int. size_t is the unsigned integer type of the result of the sizeof operator.

    记住,参数类型是size_t,大小可能不同于int. size_t是sizeof运算符结果的无符号整数类型。

    void *malloc(size_t size);
    
  5. Passing a negative int to malloc() acts like:

    将负整数传递给malloc()行为如下:

    malloc((size_t) some_negative_int) -->
    malloc(some_large_size_t)
    
  6. Check the result.

    检查结果。

    if (sequence == NULL) Handle_OutOfMemory();
    
  7. Eventually, free the pointer. It is OK to free the pointer even if it has a NULL value.

    最终,*的指针。即使它具有空值,也可以释放指针。

    free(sequence);
    
  8. If there is a chance sequence will get used again after free-ing, best to promptly set its value to NULL.

    如果有一个偶然的序列将在空闲后再次使用,最好立即将其值设置为NULL。

    free(sequence);
    sequence = NULL;
    
  9. An allocation of 0 may or may not return NULL and is not an out-of-memory condition.

    分配的0可能返回NULL,也可能不返回NULL,也不是内存不足的情况。

    double* sequence = malloc(sizeof *sequence * numInSeq);
    // If `numInSeq` could have a zero value, add test
    if (sequence == NULL && numInSeq != 0) {
      Handle_OutOfMemory();
    }
    

#1


3  

Use <stdlib.h> or <cstdlib> as suggested by Scott, also, always make sure malloc return valid pointer by NULL check.

使用< stdlib。根据Scott建议的h>或 ,也要确保malloc返回有效指针为空检查。

//malloc unable to allocate memory
if(sequence == NULL)
{
//return;
}

At the end, use free to freeup memory and to avoid memory leak.

最后,使用空闲内存,以避免内存泄漏。

free(sequence);

#2


5  

Make sure to include <stdlib.h>.

确保包括

#3


2  

Important points while using malloc :

使用malloc时的要点:

  1. Malloc function call returns you the void pointer which points to the memory location , So you should cast it to your desired data type pointer explicitly.

    Malloc函数调用返回指向内存位置的空指针,因此您应该显式地将其转换为所需的数据类型指针。

  2. You should always remember to free the memory which you dynamically allocated using malloc. (very imp)

    您应该始终记得释放使用malloc动态分配的内存。(imp)

  3. You should always check if malloc function call was successful or not.

    您应该经常检查malloc函数调用是否成功。

FYI check this link: http://www.cplusplus.com/reference/cstdlib/malloc/

FYI检查这个链接:http://www.cplusplus.com/reference/cstdlib/malloc/。

Hope this helps.

希望这个有帮助。

#4


2  

How to use malloc correctly in C?

如何在C中正确使用malloc ?

  1. Be sure to include the correct header file. That fixes OP's compiler warning.

    确保包含正确的头文件。修正了OP的编译器警告。

    #include <stdlib.h>
    
  2. Casting the return is allowed but frowned upon in C as being unnecessary. Other may disagree, so best to follow your group's coding standard.

    在C语言中,选择return是允许的,但在C中是不允许的。其他的可能不同意,所以最好遵循你的团队的编码标准。

    double* sequence = /* cast not required */ malloc(...);
    
  3. Consider the follow style as it is easier to code, review, maintain and IMO, less error prone.

    考虑下面的样式,因为它更容易编码、检查、维护和IMO,更容易出错。

    // object_pointer = malloc(sizeof *object_pointer * num_elements);
    // Example
    double* sequence = malloc(sizeof *sequence * numInSeq);
    
  4. Remember the argument type is size_t and may differ in size than int. size_t is the unsigned integer type of the result of the sizeof operator.

    记住,参数类型是size_t,大小可能不同于int. size_t是sizeof运算符结果的无符号整数类型。

    void *malloc(size_t size);
    
  5. Passing a negative int to malloc() acts like:

    将负整数传递给malloc()行为如下:

    malloc((size_t) some_negative_int) -->
    malloc(some_large_size_t)
    
  6. Check the result.

    检查结果。

    if (sequence == NULL) Handle_OutOfMemory();
    
  7. Eventually, free the pointer. It is OK to free the pointer even if it has a NULL value.

    最终,*的指针。即使它具有空值,也可以释放指针。

    free(sequence);
    
  8. If there is a chance sequence will get used again after free-ing, best to promptly set its value to NULL.

    如果有一个偶然的序列将在空闲后再次使用,最好立即将其值设置为NULL。

    free(sequence);
    sequence = NULL;
    
  9. An allocation of 0 may or may not return NULL and is not an out-of-memory condition.

    分配的0可能返回NULL,也可能不返回NULL,也不是内存不足的情况。

    double* sequence = malloc(sizeof *sequence * numInSeq);
    // If `numInSeq` could have a zero value, add test
    if (sequence == NULL && numInSeq != 0) {
      Handle_OutOfMemory();
    }