Chib Chib - 1 year ago 83
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;

void main(int argc, char **argv){
int strlen = 12;
int *newptr = stringy(strlen);

Answer Source

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

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


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*’).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download