简体   繁体   中英

How to Use malloc correctly in C?

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.

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)'

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.

确保包含<stdlib.h>

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

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

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

free(sequence);

How to use malloc correctly in C?

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

     #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.

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

     // 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.

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

     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 .

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

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

Important points while using 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.

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

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

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

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM