18

For example:

int *start;
start = (int*)malloc(40);

If I wanted to iterate through all 40 bytes, how would I do so? I tried doing something like:

while(start != NULL){
     start++;
}

but that iterates through a massive number of values, which is much greater than 40. Thus, how do you ensure that you iterate through all 40 bytes.

Thanks for all the help.

svsav
  • 828
  • 3
  • 12
  • 29
  • 8
    I don't see reason for down voting the question, there is reasonable input and effort showing what the OP wants to do. What happened to SO lately – fkl Apr 28 '15 at 02:32
  • I can't remember the rationale, but look it up on SO. You should never cast the result returned by malloc. Remove the (int *) from line start=...malloc... ; – phil Apr 28 '15 at 04:38
  • 2
    It has to be taught rather than silently downvoted. Reason is available in detail in other question on SO, but it is that casting malloc's return value can POSSIBLY hide/tamper a failed allocation. Note that this is specific to C. In C++, it is a requirement to do so. – fkl Apr 28 '15 at 16:32

4 Answers4

18

There are two issues here.

A single ptr++ skips as many bytes as the type of element it points to.

Here the type is int, so it would skip 4 bytes each time (assuming a 32 bit machine since integer is 4 bytes (32 bits) there).

If you want to iterate through all 40 bytes (one byte at a time), iterate using say a char data type (or type cast your int* to char* and then increment)

The other problem is your loop termination.

There is no one putting a NULL at the end here, so your loop would keep running (and pointer advancing forward) until it runs into may be a null or goes out of your allotted memory area and crashes. The behavior is undefined.

If you allocated 40 bytes, you have to terminate at 40 bytes yourself.

It is worth mentioning that type casting the result of malloc is not a good idea in C. The primary reason is that it could potentially tamper a failed allocation. It is a requirement in C++ though. The details can be found in the exact same question on SO. Search "casting return value of malloc"

miken32
  • 42,008
  • 16
  • 111
  • 154
fkl
  • 5,412
  • 4
  • 28
  • 68
  • The type was not defined by me (by the professor), and therefore must be an int. Is there any way that I could go through the bytes with an int? – svsav Apr 28 '15 at 02:26
  • I was updating the answer, see that – fkl Apr 28 '15 at 02:28
  • you can always cast an int to a char and then do a ++. I intentionally want you to try it out, instead of me writing it down here – fkl Apr 28 '15 at 02:29
11

First of all, you should be allocating ints correctly:

int* start = malloc( sizeof( int )*40 ) ;

Then you can use array subscripting:

for( size_t i = 0 ; i < 40 ; i++ )
{
    start[i] = 0 ;
}

or a pointer to the end of the allocated memory:

int* end = start+40 ;
int* iter = start ;

while( iter < end )
{
    *iter= 0 ;
    iter++ ;
}
2501
  • 25,460
  • 4
  • 47
  • 87
3

Arrays represent contiguous blocks of memory. Since the name of the array is basically a pointer to the first element, you can use array notation to access the rest of the block. Remember though, there is no error checking by C on the bounds of the array, so if you walk off the end of the memory block, you can do all kinds of things that you didn't intend and more than likely will end up with some sort of memory fault or segmentation error. Since your int can be variable size, I would use this code instead:

int *start;
int i;

start = malloc(40 * sizeof(int));

for (i = 0; i < 40; i++)
  {
    start[i] = 0;
  }

Something like that will work nicely. The way that you are doing it, at least from the code that you posted, there is no way to stop the loop because once it exceeds the memory block, it will keep going until it runs into a NULL or you get a memory fault. In other words, the loop will only exit if it runs into a null. That null may be within the block of memory that you allocated, or it may be way beyond the block.

EDIT: One thing I noticed about my code. It will allocate space for 40 ints which can be either 4 bytes, 8 bytes, or something else depending on the architecture of the machine you are working on. If you REALLY only want 40 bytes of integers, then do something like this:

int *start;
int i;
int size;

size = 40/sizeof(int);
start = malloc(size);
for (i = 0; i < size; i++)
  {
    start[i] = 0;
  }

Or you can use a char data type or an unsigned char if you need to. One other thing that I noticed. The malloc function returns a void pointer type which is compatible with all pointers, so there is no need to do a typecast on a malloc.

Daniel Rudy
  • 1,411
  • 12
  • 23
  • You might wanna change 'points' to pointers in first line. Also it is better to say "Arrays decay into pointers in terms of access". Array is not a pointer nor vice versa – fkl Apr 28 '15 at 02:39
  • I saw that and just corrected it. I disagree with your array terminology though. The way that I learned it was that arrays are basically pointers. The pointer points to a block of memory and you use array notation to access different areas of that block. – Daniel Rudy Apr 28 '15 at 02:42
  • Arrays are not pointers. This is one of the most common misconception found around. Again the precise correct statement is "Array name decays into pointer to first element", this is where similarity ends. Please read some good reference. If needed i can certainly suggest too – fkl Apr 28 '15 at 02:45
0

Well arrays in C aren't bounded so, a few options, the most common:

int *start;
int cnt = 0;
start = (int*)malloc(sizeof(int)*40);;

while(cnt<40)
{
    start++;
    cnt++;
}

Another option:

int *start;
int *ref;
start = ref = (int*)malloc(sizeof(int)*40);

while(start != ref+40)
    start++;

And this last one is the closest to what you seem to mean to do:

int *start;
start = ref = (int*)malloc(sizeof(int)*41);
start[40] = -1;

while((*start) != -1)
    start++;

I would suggest reading more on how pointers in C work. You don't appear to have a very good grasp of it. Also, remember that C takes off the training wheels. Arrays aren't bounded or terminated in a standard way, and a pointer (address in memory) will never be NULL after iterating through an array, and the contents a pointer is pointing to could be anything.