[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: alloc
From: |
Gary Polhill |
Subject: |
Re: alloc |
Date: |
Fri, 07 Apr 2000 10:54:53 +0100 |
> Lorenzo wrote:
>
> I'm a newbye in objective-C. If I write in c:
>
> #include <stdio.h>
> #include <malloc.h>
>
> int main();
> int main()
> {
> int i, j;
> int numCol[5]={8,8,8,9,10};
> char *Ipezzo[5];
> char **labelsHist;
>
> labelsHist=(char **) malloc(sizeof (char *) * 5);
> for(i=0;i<5;i++)
> {
> Ipezzo[i]=(char *) malloc(sizeof (char) * 2);
> labelsHist[i]=(char *) malloc(sizeof (char) * numCol[i]);
> }
> for(i=0;i<5;i++)
> {
> Ipezzo[i]="x=";
> for (j=0;j<2;j++)
> labelsHist[i][j]=Ipezzo[i][j];
> }
> return 0;
> }
>
> I have no trouble. If I try to write the method for an object:
>
> - aggiornaFeedHist
> {
> int i, j;
> int numCol[5]={8,8,8,9,10};
> char *Ipezzo[5];
> char **labelsHistp;
>
> labelsHistp = [[self getZone] alloc: (sizeof (char *) * 5)];
> for(i=0;i<5;i++)
> {
> Ipezzo[i]=[[self getZone] alloc: (sizeof (char) * 2)];
> labelsHistp[i]=[[self getZone] alloc: (sizeof (char) * numCol[i])];
> /****/ labelsHistp[i]="";
> }
> for(i=0;i<5;i++)
> {
> Ipezzo[i]="x=";
> for (j=0;j<2;j++)
> labelsHistp[i][j]=Ipezzo[i][j]; ***
> }
>
> return self;
> }
>
> after *** I have segmentation fault.Why? Could somebody help me?
The line marked /****/ above does not appear in your C program. If
it did, then it would crash too. If you remove that line, then
your program won't seg fault, but I venture that it will leak memory
like a digital sieve. If you want to make sure that labelsHistp[i]
is a null string, then replace the marked line with something like
labelsHistp[i][0] = '\0'; or even memset(labelsHistp[i], 0, numCol[i]);
(or if Zone provides a calloc method (it doesn't in 1.4.1) then use
that). To avoid leaking memory, you need to replace the line:
Ipezzo[i]="x=";
with something like
strcpy(Ipezzo[i], "x=");
and when you allocate memory for Ipezzo[i], give it three characters
rather than 2. (The extra character is for the null ('\0') string
terminator.)
Apologies if this is all obvious....
Gary
--
Macaulay Land Use Research Institute, Craigiebuckler, Aberdeen. AB15 8QH
Tel: +44 (0) 1224 318611 Email: address@hidden
==================================
Swarm-Support is for discussion of the technical details of the day
to day usage of Swarm. For list administration needs (esp.
[un]subscribing), please send a message to <address@hidden>
with "help" in the body of the message.
- alloc, Lorenzo, 2000/04/07
- Re: alloc,
Gary Polhill <=