user5410809
user5410809

Reputation: 73

How to dynamically allocate memory for a single dimension array of length 30,000?

I am a student studying for a test next week on Dynamic Memory Allocation in C. I am looking at old test questions and have come across one that says to:

Write a C program that dynamically creates a single dimension array of length 30,000 and initialize the array with random numbers from 0 to 9.

I have a solid understanding of how to create the random numbers and place them into an array but I am confused about my malloc statement and how to place numbers other than the 'sizeof' code inside of it. For example, I have this code that allocates memory for a float:

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

float* func();

int main(void)
{
    int i;
    float* x;
    float array[0];

    x=func();
    srand(time(NULL));
    i=random()%10;
    array[i];
 }
 float * func(void)
 {
     float z;
     float* ptr;
     ptr = malloc(30000 * sizeof(float));
     if(ptr == NULL)
     {
         puts("ALLOCATION FAILED.\n");
     }else{
         ptr = &z;
         return ptr;
     }
}

My question is how can i dynamically allocate memory for a single dimension array of length 30,000? What sort of things would this allocation be useful for for say a real world software development job?

Upvotes: 0

Views: 2011

Answers (2)

Linus
Linus

Reputation: 1518

Perhaps using calloc makes more sense. The first parameter is the amount of elements in your block of memory (i.e an array of size 30 000). The second parameter is the size of one block (i.e one element in the array).

So you'd call it like this:

ptr = calloc(30000, sizeof(float));

There's one bottleneck with using calloc in your situation since zeroing out the memory may take a little time. You can do the same thing with malloc and instead you'd do this which leaves ptr uninitialized.

ptr = malloc(30000 * sizeof(float));

Also please don't cast the result of calloc or malloc.

EDIT: Since you changed your question to address the problem you first asked for there are several other issues with your code. Starting of with formatting issues, you should add a blankspace after the include directive. Also your prototype is incorrect since it says that func can accept any amount of parameters since it specifies a function with undefined arguments thus you should use the keyword void instead:

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

float* func(void);

Later in your function definition you have the asterisk in the middle whereas you have it to the left in your prototype. Please be consistent.

And your declaration of array is redundant since you never use it (atleast you shouldn't because you allocate memory for a dynamic array instead).

Your logic to set the numbers in the dynamic array is not working. You're trying to access your empty static array with a random index between 0 and 9 which will most likely crash. I think you meant to go through each element of your dynamic array and assign a random integer between 0 and 9, finally random() is not a function in C; you want rand():

x=func(); // allocate memory for x
srand(time(NULL)); // set a random seed for psuedo-random functions
for(i=0;i<30000;i++) {
  x[i] = rand() % 10; // assign a random number between 0 and 9.
}

In your function to allocate memory you are overriding the pointer to the dynamic array with an unitialized array which will crash your program later when trying to access it since it has no memory assigned to it. You can also replace your puts error message with perror to get more detailed information on why the allocation failed.

 ptr = malloc(30000 * sizeof(float));
 if(ptr == NULL) {
     perror("malloc failed");
     // handle error
 }else {
     return ptr;
 }

Upvotes: 4

too honest for this site
too honest for this site

Reputation: 12263

There are so many errors in your code. I'll try to list them (text after each line):

float* func(void);

Use prototype-declarators. C is not C++!

float array[0];

This is useless, as you are supposed to alloc an array dynamically.

x=func();

Allocation might fail. Always check for errors: if ( (x = func) == NULL ) { printf("Allocation failure."); exit(1); }

i=random()%10;
array[i];

i is uninitialised. And you need a loop over all elements pointed to by x. array is just a local array. This is undefined behaviour. Avoid it like hell (or whatever you fear most).

float * func(void)

Funny enough here you have the correct type. Note that this is not identical to the declaration above! Enable compiler warnings and py heed to them, your compiler should complain.

float z;

What for?

ptr = malloc(30000 * sizeof(float));

Here is a goodie: This is correct! You should not cast void * in C.

if(ptr == NULL)
{
    puts("ALLOCATION FAILED.\n");

Fine, you have the message here. But you still return, so the caller also has to check. Unless you exit(1) here laready - this is allowed, but not good style.

ptr = &z;

Here you overwrite the pointer to the allocated array and set it to a local variable. You also cannot free the allocated array anymore, because you lost its address. Just remove this line along with the definition of z; they are useless (and this line is also wrong). This is the major fault

return ptr;

Now you return an invalid memory address. Never return the address of a local variable. This goes out of life once you leave the block it is defined (here: the function).

Upvotes: 2

Related Questions