Chib Chib - 14 days ago 9
C Question

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);
}

Answer

Seems like there is a typo in your code. Change line

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

to

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

Also, it's better to type-cast the malloc to (int *), like this

int *ptr = (int *) malloc(sizeof(int)*length);

since malloc returns a pointer of type void *, although implicit type-casting exists in C, it's still a good practice to do that. But if you try to compile this code using g++, it would show an error (invalid conversion from ‘void*’ to ‘int*’).