Chib
Chib

Reputation: 11

Pointer to Nothing When Using malloc?

As far as I can tell I've followed the advice given by other users, but I still get a segfault when I try to return a pointer to an array. The printf in main returns nothing, so I'm guessing that the pointer isn't to anything on the heap?

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

int * stringy(int length){
   int *ptr = malloc(sizeof(int)*length);
   int i;
   for(i = 0; 1 < length; i++){
      ptr[i] = i;
   }
   return(ptr);
}

void main(int argc, char **argv){
   int strlen = 12;
   int *newptr = stringy(strlen);
   printf("%d\n",newptr[0]);
   free(newptr);
}

Upvotes: 0

Views: 194

Answers (2)

Jarvis
Jarvis

Reputation: 8564

It seems like there is a typo in your code. Instead of

for(i = 0; 1 < length; i++){

, it looks like you meant

for(i = 0; i < length; i++){

Upvotes: 6

Leonora Tindall
Leonora Tindall

Reputation: 1521

You need to check for null pointers; malloc returns NULL when it can't allocate the memory you requested, and that would cause the problem you're referring to. Also, you should cast your pointer to int *.

The actual problem, however, is that you have a typo; rather than 1 < length, your for loop condition should read i < length. Your for loop runs forever.

Upvotes: 1

Related Questions